xref: /csrg-svn/share/doc/psd/20.ipctut/pipe.c (revision 27700)
1*27700Smckusick .\" Copyright (c) 1986 Regents of the University of California.
2*27700Smckusick .\" All rights reserved.  The Berkeley software License Agreement
3*27700Smckusick .\" specifies the terms and conditions for redistribution.
4*27700Smckusick .\"
5*27700Smckusick .\"	@(#)pipe.c	6.1 (Berkeley) 05/04/86
6*27700Smckusick .\"
7*27700Smckusick #include <stdio.h>
8*27700Smckusick 
9*27700Smckusick #define DATA "Bright star, would I were steadfast as thou art . . ."
10*27700Smckusick 
11*27700Smckusick /*
12*27700Smckusick  * This program creates a pipe, then forks.  The child communicates to the
13*27700Smckusick  * parent over the pipe. Notice that a pipe is a one-way communications
14*27700Smckusick  * device.  I can write to the output socket (sockets[1], the second socket
15*27700Smckusick  * of the array returned by pipe()) and read from the input socket
16*27700Smckusick  * (sockets[0]), but not vice versa.
17*27700Smckusick  */
18*27700Smckusick 
19*27700Smckusick main()
20*27700Smckusick {
21*27700Smckusick 	int             sockets[2], child;
22*27700Smckusick 
23*27700Smckusick 	/* Create a pipe */
24*27700Smckusick 	if (pipe(sockets) < 0)
25*27700Smckusick 		perror("opening stream socket pair");
26*27700Smckusick 
27*27700Smckusick 	if (child = fork()) {
28*27700Smckusick 		char            buf[1024];
29*27700Smckusick 
30*27700Smckusick 		/* This is still the parent.  It reads the child's message. */
31*27700Smckusick 		close(sockets[1]);
32*27700Smckusick 		if (read(sockets[0], buf, 1024) < 0)
33*27700Smckusick 			perror("reading message");
34*27700Smckusick 		printf("-->%s\en", buf);
35*27700Smckusick 		close(sockets[0]);
36*27700Smckusick 	} else {
37*27700Smckusick 		/* This is the child.  It writes a message to its parent. */
38*27700Smckusick 		close(sockets[0]);
39*27700Smckusick 		if (write(sockets[1], DATA, sizeof(DATA)) < 0)
40*27700Smckusick 			perror("writing message");
41*27700Smckusick 		close(sockets[1]);
42*27700Smckusick 	}
43*27700Smckusick }
44