tighten up code to reduce wasted paper
[unix-history] / usr / src / share / doc / psd / 20.ipctut / ustreamread.c
CommitLineData
23237d2e
KM
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.\"
7f478b3b 5.\" @(#)ustreamread.c 6.2 (Berkeley) %G%
23237d2e
KM
6.\"
7#include <sys/types.h>
8#include <sys/socket.h>
9#include <sys/un.h>
10#include <stdio.h>
11
23237d2e
KM
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 */
23237d2e
KM
21main()
22{
23 int sock;
24 struct sockaddr_un server;
25 int msgsock;
26 char buf[1024];
7f478b3b 27 int rval, i;
23237d2e
KM
28
29 /* Create socket */
30 sock = socket(AF_UNIX, SOCK_STREAM, 0);
31 if (sock < 0) {
32 perror("opening stream socket");
33 exit(0);
34 }
35 /* Name socket using file system name */
36 server.sun_family = AF_UNIX;
37 strcpy(server.sun_path, NAME);
38 if (bind(sock, &server, sizeof(struct sockaddr_un))) {
39 perror("binding stream socket");
40 }
41 printf("Socket has name %s\en", server.sun_path);
23237d2e
KM
42 /* Start accepting connections */
43 listen(sock, 5);
7f478b3b 44 for (;;) {
23237d2e
KM
45 msgsock = accept(sock, 0, 0);
46 do {
47 for (i = 0; i < 1024; i++)
48 buf[i] = '\e0';
49 if ((rval = read(msgsock, buf, 1024)) < 0)
50 perror("reading stream message");
51 if (rval == 0) {
52 printf("Ending connection\en");
53 } else {
54 printf("-->%s\en", buf);
55 };
56 } while (rval != 0);
57 close(msgsock);
7f478b3b 58 }
23237d2e
KM
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 unlink(NAME);
69 close(sock);
70}