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