|
CS473 - Computer Networks
| Displaying exercises/e4/solution/listen.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/wait.h>
#define BUFSIZE 4096
char *sock_path = "/tmp/listen";
void clear(void)
{
pid_t pid = fork();
if (pid < 0) perror("fork");
else if (pid == 0) {
execlp("clear", "clear", NULL);
perror("execlp");
exit(0);
} else {
wait(NULL);
}
}
void cleanup(int sig)
{
unlink(sock_path);
exit(0);
}
int main(int argc, char *argv[])
{
struct sockaddr_un name;
char buf[BUFSIZE];
int r;
if (argc > 1) sock_path = strdup(argv[1]);
signal(SIGINT, cleanup);
/* Create socket, initially un-connected. */
int sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sock < 0) {
perror("socket");
exit(1);
}
/* Create name (filesystem socket file) */
name.sun_family = AF_UNIX;
strcpy(name.sun_path, sock_path);
/* Abort if socket file is present */
if (access(sock_path, F_OK) == 0) {
printf("Socket file %s already exists, aborting.\n", sock_path);
exit(0);
}
/* Bind socket to name: */
if (bind(sock, (struct sockaddr *)&name, sizeof(struct sockaddr_un))) {
perror("bind");
exit(1);
}
clear();
gethostname(buf, BUFSIZE);
printf("Login to %s and say at %s\n", buf, sock_path);
while((r = read(sock, buf, BUFSIZE)) > 0) {
write(STDOUT_FILENO, buf, r);
}
return 0;
}
|