I'm not understanding the output of this program:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
int i = 0;
int main()
{
while(i<3)
{
fork();
printf("%d\n",i);
++i;
}
}
The output is:
0
1
2
2
1
2
0
1
2
2
2
1
2
2
Can please someone tell me how I should tackle this issue in order to fully understand why I'm getting this output?
Change your code to this and the output should make a lot more sense:
Fork will make a copy of the process. An independent copy of the process. So, if a global variable contains 3 at the time you fork, each copy of the process gets their very own 3. And if they modify, their modifications are completely independent.
It's something like...
...etc
The order that the processes are outputting in, however, is undetermined, so you likely won't see the exact same output every time, and even if you do it's not something you can guarantee.
As other people said, each process has its own global 'i' that it keeps track of, and its value is simply the value of the forking process's i at the fork.
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 ofi
.Each of its children will continue the loop from the
fork()
call by printing out its initiali
value, incrementing and looping. This means that children 0 will print 0, 1, and 2, and spawn two new children, with "initial" values ofi
1 and 2. Children 1 will print 1 and 2 and spawn one more children, with an "initial" value ofi
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.
Try using pthreads if you want to create a thread inside the process for concurrent programming. The function you want is pthread_create and pthread_join for tidying up later.
Something like this:
But perhaps not, depending on your actual needs.