127700Smckusick .\" Copyright (c) 1986 Regents of the University of California. 227700Smckusick .\" All rights reserved. The Berkeley software License Agreement 327700Smckusick .\" specifies the terms and conditions for redistribution. 427700Smckusick .\" 5*27883Skarels .\" @(#)pipe.c 6.2 (Berkeley) 05/08/86 627700Smckusick .\" 727700Smckusick #include <stdio.h> 827700Smckusick 927700Smckusick #define DATA "Bright star, would I were steadfast as thou art . . ." 1027700Smckusick 1127700Smckusick /* 1227700Smckusick * This program creates a pipe, then forks. The child communicates to the 1327700Smckusick * parent over the pipe. Notice that a pipe is a one-way communications 1427700Smckusick * device. I can write to the output socket (sockets[1], the second socket 1527700Smckusick * of the array returned by pipe()) and read from the input socket 1627700Smckusick * (sockets[0]), but not vice versa. 1727700Smckusick */ 1827700Smckusick 1927700Smckusick main() 2027700Smckusick { 21*27883Skarels int sockets[2], child; 2227700Smckusick 2327700Smckusick /* Create a pipe */ 24*27883Skarels if (pipe(sockets) < 0) { 2527700Smckusick perror("opening stream socket pair"); 26*27883Skarels exit(10); 27*27883Skarels } 2827700Smckusick 29*27883Skarels if ((child = fork()) == -1) 30*27883Skarels perror("fork"); 31*27883Skarels else if (child) { 32*27883Skarels char buf[1024]; 3327700Smckusick 3427700Smckusick /* This is still the parent. It reads the child's message. */ 3527700Smckusick close(sockets[1]); 3627700Smckusick if (read(sockets[0], buf, 1024) < 0) 3727700Smckusick perror("reading message"); 3827700Smckusick printf("-->%s\en", buf); 3927700Smckusick close(sockets[0]); 4027700Smckusick } else { 4127700Smckusick /* This is the child. It writes a message to its parent. */ 4227700Smckusick close(sockets[0]); 4327700Smckusick if (write(sockets[1], DATA, sizeof(DATA)) < 0) 4427700Smckusick perror("writing message"); 4527700Smckusick close(sockets[1]); 4627700Smckusick } 4727700Smckusick } 48