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