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.1 (Berkeley) 05/04/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 27 if (child = fork()) { 28 char buf[1024]; 29 30 /* This is still the parent. It reads the child's message. */ 31 close(sockets[1]); 32 if (read(sockets[0], buf, 1024) < 0) 33 perror("reading message"); 34 printf("-->%s\en", buf); 35 close(sockets[0]); 36 } else { 37 /* This is the child. It writes a message to its parent. */ 38 close(sockets[0]); 39 if (write(sockets[1], DATA, sizeof(DATA)) < 0) 40 perror("writing message"); 41 close(sockets[1]); 42 } 43 } 44