I\'m not understanding the output of this program:
#include
#include
#include
int i = 0;
int main()
{
When you fork(), a complete copy of the current process is created in its current state. This means that your initial process will create three new processes that are in the middle of the while loop, with i
being respectively 0, 1, and 2 in each one of them. It will also print his own values of i
.
Each of its children will continue the loop from the fork()
call by printing out its initial i
value, incrementing and looping. This means that children 0 will print 0, 1, and 2, and spawn two new children, with "initial" values of i
1 and 2. Children 1 will print 1 and 2 and spawn one more children, with an "initial" value of i
of 2. Children 2 will print 2 and leave the loop.
If you continue this reasoning you will come to the conclusion that in total two 0's, four 1's and eight 2's will be printed. But, since the order of execution depends on how the OS schedules the concurrent processes, you cannot have guarantees on the order those are printed.