xref: /freebsd/share/doc/psd/20.ipctut/pipe.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
1 .\" Copyright (c) 1986, 1993
2 .\"	The Regents of the University of California.  All rights reserved.
3 .\"
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
6 .\" are met:
7 .\" 1. Redistributions of source code must retain the above copyright
8 .\"    notice, this list of conditions and the following disclaimer.
9 .\" 2. Redistributions in binary form must reproduce the above copyright
10 .\"    notice, this list of conditions and the following disclaimer in the
11 .\"    documentation and/or other materials provided with the distribution.
12 .\" 3. Neither the name of the University nor the names of its contributors
13 .\"    may be used to endorse or promote products derived from this software
14 .\"    without specific prior written permission.
15 .\"
16 .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
17 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
20 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 .\" SUCH DAMAGE.
27 .\"
28 #include <stdio.h>
29 
30 #define DATA "Bright star, would I were steadfast as thou art . . ."
31 
32 /*
33  * This program creates a pipe, then forks.  The child communicates to the
34  * parent over the pipe. Notice that a pipe is a one-way communications
35  * device.  I can write to the output socket (sockets[1], the second socket
36  * of the array returned by pipe()) and read from the input socket
37  * (sockets[0]), but not vice versa.
38  */
39 
40 main()
41 {
42 	int sockets[2], child;
43 
44 	/* Create a pipe */
45 	if (pipe(sockets) < 0) {
46 		perror("opening stream socket pair");
47 		exit(10);
48 	}
49 
50 	if ((child = fork()) == -1)
51 		perror("fork");
52 	else if (child) {
53 		char buf[1024];
54 
55 		/* This is still the parent.  It reads the child's message. */
56 		close(sockets[1]);
57 		if (read(sockets[0], buf, 1024) < 0)
58 			perror("reading message");
59 		printf("-->%s\en", buf);
60 		close(sockets[0]);
61 	} else {
62 		/* This is the child.  It writes a message to its parent. */
63 		close(sockets[0]);
64 		if (write(sockets[1], DATA, sizeof(DATA)) < 0)
65 			perror("writing message");
66 		close(sockets[1]);
67 	}
68 }
69