I have executed a block of code. And it is as shown below:
#include<stdio.h>
main() {
int i=0;
fork();
printf("The value of i is:%d\n",++i);
fork();
printf("The value of j is:%d\n",++i);
fork();
wait();
}
And I got following output:
The value of i is:1
The value of j is:2
The value of i is:1
The value of j is:2
The value of j is:2
pckoders@ubuntu:~$ The value of j is:2
Can anyone explain to me what role fork() and wait() functions play here?
The program generates a tree of processes. At every
fork, this tree branches in two. If you grab a piece of paper, it’s not very hard to draw this tree; the only thing that’s hard is getting theivalues right due to your use of prefix++. If you let each of the processsleepfor a few seconds at the end, you can also observe the tree using thepstreeprogram.Each one of the processes then runs the
waitsystem call, which waits for any one of its child processes (child nodes in the process tree) to finish.