Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/wait.h>
- int cnt;
- int query(int a)
- {
- cnt++;
- return a;
- }
- int main()
- {
- int fd[2];
- pipe(fd); //init pipe
- int pid=fork(); //create a copy of our process
- if (pid) //parent process
- {
- close(fd[1]); //close write descriptor
- int result;
- if (pid!=-1)
- {
- waitpid(pid,0,0); //wait for child to finish
- read(fd[0], &result, sizeof(result)); //read result
- }
- else
- {
- fprintf(stderr,"forking failed..\n");
- return 1;
- }
- printf("parent used %d calls\n",cnt);
- printf("result = %d\n",result);
- }
- else //child process
- {
- close(fd[0]); //close read descriptor
- //compute result with a suboptimal amount of calls
- int result=0;
- for (int i=0; i<10; i++)
- result+=query(i);
- printf("child used %d calls\n",cnt);
- write(fd[1], &result, sizeof(result)); //send result
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement