1 .\" Copyright (c) 1986 Regents of the University of California. 2 .\" All rights reserved. The Berkeley software License Agreement 3 .\" specifies the terms and conditions for redistribution. 4 .\" 5 .\" @(#)ustreamread.c 6.1 (Berkeley) 05/04/86 6 .\" 7 #include <sys/types.h> 8 #include <sys/socket.h> 9 #include <sys/un.h> 10 #include <stdio.h> 11 12 #define TRUE 1 13 #define NAME "socket" 14 15 /* 16 * This program creates a socket in the UNIX domain and binds a name to it. 17 * After printing the socket's name it begins a loop. Each time through the 18 * loop it accepts a connection and prints out messages from it. When the 19 * connection breaks, or a termination message comes through, the program 20 * accepts a new connection. 21 */ 22 23 main() 24 { 25 int sock; 26 struct sockaddr_un server; 27 int msgsock; 28 char buf[1024]; 29 int rval; 30 int i; 31 32 /* Create socket */ 33 sock = socket(AF_UNIX, SOCK_STREAM, 0); 34 if (sock < 0) { 35 perror("opening stream socket"); 36 exit(0); 37 } 38 /* Name socket using file system name */ 39 server.sun_family = AF_UNIX; 40 strcpy(server.sun_path, NAME); 41 if (bind(sock, &server, sizeof(struct sockaddr_un))) { 42 perror("binding stream socket"); 43 } 44 printf("Socket has name %s\en", server.sun_path); 45 46 /* Start accepting connections */ 47 listen(sock, 5); 48 do { 49 msgsock = accept(sock, 0, 0); 50 do { 51 for (i = 0; i < 1024; i++) 52 buf[i] = '\e0'; 53 if ((rval = read(msgsock, buf, 1024)) < 0) 54 perror("reading stream message"); 55 if (rval == 0) { 56 printf("Ending connection\en"); 57 } else { 58 printf("-->%s\en", buf); 59 }; 60 } while (rval != 0); 61 close(msgsock); 62 } while (TRUE); 63 /* 64 * The following statements are not executed, because they follow an 65 * infinite loop. However, most ordinary programs will not run 66 * forever. In the UNIX domain it is necessary to tell the file 67 * system that one is through using NAME. in most programs one uses 68 * the call unlink() as below. Since the user will have to kill this 69 * program, it will be necessary to remove the name by a command from 70 * the shell. 71 */ 72 unlink(NAME); 73 close(sock); 74 } 75