JoelKatz

http://stackoverflow.com/questions/19378734/how-to-make-chil

Oct 15th, 2013
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sched.h>
  4. #include <wait.h>
  5. #include <stdlib.h>
  6.  
  7. int  a;
  8. pid_t pid;
  9. int main(void)
  10. {
  11.  
  12. a=10;
  13. //declare and create 2 pipes
  14. int p1[2], p2[2];
  15. pipe(p1);
  16. pipe(p2);
  17. int ra;
  18.  for(int i=0;i<3;i++)
  19.  {
  20.    pid = fork();
  21.    if (pid==0)
  22.    {
  23.       close(p1[1]);
  24.       close(p2[0]);
  25.       if (read(p1[0],&ra,sizeof(int)) != sizeof(int))
  26.        _exit(0);
  27.       while(ra>0)
  28.       {
  29.         ra-=1;
  30.         printf("%i a are available, reported by process %i\n",ra,getpid());
  31.         write(p2[1],&ra,sizeof(int));
  32.         sched_yield();
  33.         if (read(p1[0],&ra,sizeof(int)) != sizeof(int))
  34.          _exit(0);
  35.       }
  36.       close(p2[1]);
  37.       close(p1[0]);
  38.       _exit(0);
  39.    }
  40.  }
  41.  
  42.  if(pid>0)    //parent process outside for loop
  43.  {
  44.     close(p1[0]);
  45.     close(p2[1]);
  46.     while (a>0)
  47.     {
  48.         write(p1[1],&a,sizeof(int));
  49.         read(p2[0],&a,sizeof(int));
  50.     }
  51.     close(p2[0]);
  52.     close(p1[1]);
  53.  
  54.  }
  55. }
Add Comment
Please, Sign In to add comment