xref: /freebsd/share/doc/psd/20.ipctut/pipe.c (revision c697fb7f)
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 .\"	@(#)pipe.c	8.1 (Berkeley) 6/8/93
29 .\"
30 #include <stdio.h>
31 
32 #define DATA "Bright star, would I were steadfast as thou art . . ."
33 
34 /*
35  * This program creates a pipe, then forks.  The child communicates to the
36  * parent over the pipe. Notice that a pipe is a one-way communications
37  * device.  I can write to the output socket (sockets[1], the second socket
38  * of the array returned by pipe()) and read from the input socket
39  * (sockets[0]), but not vice versa.
40  */
41 
42 main()
43 {
44 	int sockets[2], child;
45 
46 	/* Create a pipe */
47 	if (pipe(sockets) < 0) {
48 		perror("opening stream socket pair");
49 		exit(10);
50 	}
51 
52 	if ((child = fork()) == -1)
53 		perror("fork");
54 	else if (child) {
55 		char buf[1024];
56 
57 		/* This is still the parent.  It reads the child's message. */
58 		close(sockets[1]);
59 		if (read(sockets[0], buf, 1024) < 0)
60 			perror("reading message");
61 		printf("-->%s\en", buf);
62 		close(sockets[0]);
63 	} else {
64 		/* This is the child.  It writes a message to its parent. */
65 		close(sockets[0]);
66 		if (write(sockets[1], DATA, sizeof(DATA)) < 0)
67 			perror("writing message");
68 		close(sockets[1]);
69 	}
70 }
71