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