Advertisement
rfmonk

socketpair.c

Nov 21st, 2013
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <stdio.h>
  4.  
  5. #define DATA1 "This is from An Introductory 4.3BSD Interprocess Communication Tutorial"
  6. #define DATA2 "practice typing and learning C sockets"
  7.  
  8. /*
  9.  * This program creates a pair of connected sockets then
  10.  * forks and communicates over them. This is very similar
  11.  * to communication with pipes, however, socketpairs are
  12.  * two-way communication objects. Therefore I can send
  13.  * messages in both directions.
  14.  */
  15.  
  16. main()
  17. {
  18.     int sockets[2], child;
  19.     char buf[1024];
  20.  
  21.     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {
  22.         perror("opening stream socket pair");
  23.         exit(1);
  24.     }
  25.  
  26.     if ((child = fork()) == -1)
  27.         perror("fork");
  28.     else if (child) { /* This is the parent. */
  29.         close(sockets[0]);
  30.         if (read(sockets[1], buf, 1024, 0) < 0)
  31.                 perror("reading stream message");
  32.         printf("-->%s\n", buf);
  33.         if (write(sockets[1], DATA2, sizeof(DATA2)) < 0)
  34.             perror("writing stream message");  
  35.         close(sockets[1]);
  36.  
  37. } else {    /* This is the child. */
  38.         close(sockets[1]);
  39.         if (write(sockets[0], DATA1, sizeof(DATA1)) < 0)
  40.             perror("writing stream message");
  41.         if (read(sockets[0], buf, 1024, 0) < 0)
  42.             perror("reading stream message");}
  43.         printf("-->%s\n", buf);
  44.         close(sockets[0]);
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement