Advertisement
nigu

pipe

Nov 17th, 2014
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6. #define MSGSIZE 16
  7.  
  8.  
  9. char *msg1="hello, world #1";
  10. char *msg2="hello, world #2";
  11. char *msg3="hello, world #3";
  12.  
  13. main() {
  14.     char inbuf[MSGSIZE];
  15.     int p[2], j;
  16.     pid_t pid;
  17.    
  18.     if(pipe(p)==-1) {
  19.         perror("pipe call");
  20.         exit(1);
  21.     }
  22.    
  23.     switch(pid=fork()) {
  24.         case -1:
  25.             perror("fork call");
  26.             _exit(2);
  27.         case 0: /* processo figlio */
  28.             close(p[0]); /* chiusura del descrittore di lettura */
  29.             /*Leggi MSGSIZE byte dal buffer msg1 e scrivi su p[1]*/
  30.             write(p[1], msg1, MSGSIZE);
  31.             write(p[1], msg2, MSGSIZE);
  32.             write(p[1], msg3, MSGSIZE);
  33.             break;
  34.         default: /* processo padre */
  35.             close(p[1]); /* chiusura del descrittore di scrittura */
  36.             for (j=0; j<3; j++) {
  37.                 /*Leggi MSGSIZE byte da p[0] e scrivi sul buffer inbuf*/
  38.                 read(p[0], inbuf, MSGSIZE);
  39.                 printf("%s\n", inbuf);
  40.             }
  41.             wait(NULL);
  42.     }
  43.     _exit(0);
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement