1 /* 2 * Copyright (c) 1986 The Regents of the University of California. 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms are permitted 6 * provided that the above copyright notice and this paragraph are 7 * duplicated in all such forms and that any documentation, 8 * advertising materials, and other materials related to such 9 * distribution and use acknowledge that the software was developed 10 * by the University of California, Berkeley. The name of the 11 * University may not be used to endorse or promote products derived 12 * from this software without specific prior written permission. 13 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR 14 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED 15 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 16 */ 17 18 #ifndef lint 19 char copyright[] = 20 "@(#) Copyright (c) 1986 The Regents of the University of California.\n\ 21 All rights reserved.\n"; 22 #endif /* not lint */ 23 24 #ifndef lint 25 static char sccsid[] = "@(#)pipe.c 6.3 (Berkeley) 03/07/89"; 26 #endif /* not lint */ 27 28 #include <stdio.h> 29 30 #define DATA "Bright star, would I were steadfast as thou art . . ." 31 32 /* 33 * This program creates a pipe, then forks. The child communicates to the 34 * parent over the pipe. Notice that a pipe is a one-way communications 35 * device. I can write to the output socket (sockets[1], the second socket 36 * of the array returned by pipe()) and read from the input socket 37 * (sockets[0]), but not vice versa. 38 */ 39 40 main() 41 { 42 int sockets[2], child; 43 44 /* Create a pipe */ 45 if (pipe(sockets) < 0) { 46 perror("opening stream socket pair"); 47 exit(10); 48 } 49 50 if ((child = fork()) == -1) 51 perror("fork"); 52 else if (child) { 53 char buf[1024]; 54 55 /* This is still the parent. It reads the child's message. */ 56 close(sockets[1]); 57 if (read(sockets[0], buf, 1024) < 0) 58 perror("reading message"); 59 printf("-->%s\en", buf); 60 close(sockets[0]); 61 } else { 62 /* This is the child. It writes a message to its parent. */ 63 close(sockets[0]); 64 if (write(sockets[1], DATA, sizeof(DATA)) < 0) 65 perror("writing message"); 66 close(sockets[1]); 67 } 68 } 69