xref: /csrg-svn/share/doc/psd/20.ipctut/pipe.c (revision 62784)
1*62784Sbostic .\" Copyright (c) 1986, 1993
2*62784Sbostic .\"	The Regents of the University of California.  All rights reserved.
348154Sbostic .\"
448154Sbostic .\" %sccs.include.redist.roff%
548154Sbostic .\"
6*62784Sbostic .\"	@(#)pipe.c	8.1 (Berkeley) 06/08/93
748154Sbostic .\"
827700Smckusick #include <stdio.h>
927700Smckusick 
1027700Smckusick #define DATA "Bright star, would I were steadfast as thou art . . ."
1127700Smckusick 
1227700Smckusick /*
1327700Smckusick  * This program creates a pipe, then forks.  The child communicates to the
1427700Smckusick  * parent over the pipe. Notice that a pipe is a one-way communications
1527700Smckusick  * device.  I can write to the output socket (sockets[1], the second socket
1627700Smckusick  * of the array returned by pipe()) and read from the input socket
1727700Smckusick  * (sockets[0]), but not vice versa.
1827700Smckusick  */
1927700Smckusick 
2027700Smckusick main()
2127700Smckusick {
2227883Skarels 	int sockets[2], child;
2327700Smckusick 
2427700Smckusick 	/* Create a pipe */
2527883Skarels 	if (pipe(sockets) < 0) {
2627700Smckusick 		perror("opening stream socket pair");
2727883Skarels 		exit(10);
2827883Skarels 	}
2927700Smckusick 
3027883Skarels 	if ((child = fork()) == -1)
3127883Skarels 		perror("fork");
3227883Skarels 	else if (child) {
3327883Skarels 		char buf[1024];
3427700Smckusick 
3527700Smckusick 		/* This is still the parent.  It reads the child's message. */
3627700Smckusick 		close(sockets[1]);
3727700Smckusick 		if (read(sockets[0], buf, 1024) < 0)
3827700Smckusick 			perror("reading message");
3927700Smckusick 		printf("-->%s\en", buf);
4027700Smckusick 		close(sockets[0]);
4127700Smckusick 	} else {
4227700Smckusick 		/* This is the child.  It writes a message to its parent. */
4327700Smckusick 		close(sockets[0]);
4427700Smckusick 		if (write(sockets[1], DATA, sizeof(DATA)) < 0)
4527700Smckusick 			perror("writing message");
4627700Smckusick 		close(sockets[1]);
4727700Smckusick 	}
4827700Smckusick }
49