1 .\" Copyright (c) 1986, 1993
2 .\"	The Regents of the University of California.  All rights reserved.
3 .\"
4 .\" %sccs.include.redist.roff%
5 .\"
6 .\"	@(#)ustreamread.c	8.1 (Berkeley) 06/08/93
7 .\"
8 #include <sys/types.h>
9 #include <sys/socket.h>
10 #include <sys/un.h>
11 #include <stdio.h>
12 
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 main()
23 {
24 	int sock, msgsock, rval;
25 	struct sockaddr_un server;
26 	char buf[1024];
27 
28 	/* Create socket */
29 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
30 	if (sock < 0) {
31 		perror("opening stream socket");
32 		exit(1);
33 	}
34 	/* Name socket using file system name */
35 	server.sun_family = AF_UNIX;
36 	strcpy(server.sun_path, NAME);
37 	if (bind(sock, &server, sizeof(struct sockaddr_un))) {
38 		perror("binding stream socket");
39 		exit(1);
40 	}
41 	printf("Socket has name %s\en", server.sun_path);
42 	/* Start accepting connections */
43 	listen(sock, 5);
44 	for (;;) {
45 		msgsock = accept(sock, 0, 0);
46 		if (msgsock == -1)
47 			perror("accept");
48 		else do {
49 			bzero(buf, sizeof(buf));
50 			if ((rval = read(msgsock, buf, 1024)) < 0)
51 				perror("reading stream message");
52 			else if (rval == 0)
53 				printf("Ending connection\en");
54 			else
55 				printf("-->%s\en", buf);
56 		} while (rval > 0);
57 		close(msgsock);
58 	}
59 	/*
60 	 * The following statements are not executed, because they follow an
61 	 * infinite loop.  However, most ordinary programs will not run
62 	 * forever.  In the UNIX domain it is necessary to tell the file
63 	 * system that one is through using NAME.  In most programs one uses
64 	 * the call unlink() as below. Since the user will have to kill this
65 	 * program, it will be necessary to remove the name by a command from
66 	 * the shell.
67 	 */
68 	close(sock);
69 	unlink(NAME);
70 }
71