Advertisement
rfmonk

intro_socket1.c

Nov 21st, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.00 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #define DATA "This is from introductory 4.4BSD IPC"
  4.  
  5. /*
  6.  * This program creates a pipe, then forks. The child communicates
  7.  * to the parent over the pipe. Notice that a pipe is a one-way
  8.  * communications device. I can write to the output socket (
  9.  * sockets[1], the second socket of the array returned by pipe())
  10.  * and read from the input socket (sockets[0]), but not vice versa.
  11.  */
  12.  
  13. main()
  14. {
  15.     int sockets[2], child;
  16.  
  17.     /* Create a pipe */
  18.     if (pipe(sockets) < 0) {
  19.         perror("opening stream socket pair");
  20.         exit(10);
  21.     }
  22.  
  23.     if ((child = fork()) == -1)
  24.         perror("fork");
  25.     else if (child) {
  26.         char buf[1024];
  27.  
  28.         /* This is still the parent. It reads the child's message. */
  29.         close(sockets[1]);
  30.         if (read(sockets[0], buf, 1024) < 0)
  31.             perror("reading message");
  32.         printf("-->%s\n", buf);
  33.         close(sockets[0]);
  34.  
  35.     } else {
  36.         /* This is the child. It writes a message to its parent. */
  37.         close(sockets[0]);
  38.         if (write(sockets[1], DATA, sizeof(DATA)) < 0 )
  39.             perror("writing message");
  40.         close(sockets[1]);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement