Advertisement
Guest User

Untitled

a guest
Aug 4th, 2015
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4.  
  5. int cnt;
  6.  
  7. int query(int a)
  8. {
  9.     cnt++;
  10.     return a;
  11. }
  12.  
  13. int main()
  14. {
  15.     int fd[2];
  16.     pipe(fd); //init pipe
  17.     int pid=fork(); //create a copy of our process
  18.     if (pid) //parent process
  19.     {
  20.         close(fd[1]); //close write descriptor
  21.        
  22.         int result;
  23.         if (pid!=-1)
  24.         {
  25.             waitpid(pid,0,0); //wait for child to finish
  26.  
  27.             read(fd[0], &result, sizeof(result)); //read result
  28.         }
  29.         else
  30.         {
  31.             fprintf(stderr,"forking failed..\n");
  32.             return 1;
  33.         }
  34.         printf("parent used %d calls\n",cnt);
  35.         printf("result = %d\n",result);
  36.     }
  37.     else //child process
  38.     {
  39.         close(fd[0]); //close read descriptor
  40.  
  41.         //compute result with a suboptimal amount of calls
  42.         int result=0;
  43.         for (int i=0; i<10; i++)
  44.             result+=query(i);
  45.        
  46.         printf("child used %d calls\n",cnt);
  47.  
  48.         write(fd[1], &result, sizeof(result)); //send result
  49.     }
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement