1 /* userver.c - simple server for Unix domain sockets */
3 /* Waits for a connection on the ./sample-socket Unix domain
4 socket. Once a connection has been established, copy data
5 from the socket to stdout until the other end closes the
6 connection, and then wait for another connection to the socket. */
9 #include <sys/socket.h>
13 #define _PATH_LOG "/dev/log"
16 /* issue an error message via perror() and terminate the program */
17 void die(char * message) {
22 /* Copies data from file descriptor 'from' to file descriptor 'to'
23 until nothing is left to be copied. Exits if an error occurs. */
24 void copyData(int from, int to) {
28 while ((amount = read(from, buf, sizeof(buf))) > 0) {
29 if (write(to, buf, amount) != amount) {
40 struct sockaddr_un address;
44 /* Remove any preexisting socket (or other file) */
47 memset(&address, 0, sizeof(address));
48 address.sun_family = AF_UNIX; /* Unix domain socket */
49 strncpy(address.sun_path, _PATH_LOG, sizeof(address.sun_path));
51 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
55 /* The total length of the address includes the sun_family
57 addrLength = sizeof(address.sun_family) +
58 strlen(address.sun_path);
60 if (bind(fd, (struct sockaddr *) &address, addrLength))
63 if (chmod(_PATH_LOG, 0666) < 0)
70 while ((conn = accept(fd, (struct sockaddr *) &address,
72 printf("---- getting data\n");
73 copyData(conn, fileno(stdout));
74 printf("---- done\n");