Visually what happens to fork() in a For Loop
Here's how to understand it, starting at the for
loop.
Loop starts in parent,
i == 0
Parent
fork()
s, creating child 1.You now have two processes. Both print
i=0
.Loop restarts in both processes, now
i == 1
.Parent and child 1
fork()
, creating children 2 and 3.You now have four processes. All four print
i=1
.Loop restarts in all four processes, now
i == 2
.Parent and children 1 through 3 all
fork()
, creating children 4 through 7.You now have eight processes. All eight print
i=2
.Loop restarts in all eight processes, now
i == 3
.Loop terminates in all eight processes, as
i < 3
is no longer true.All eight processes print
hi
.All eight processes terminate.
So you get 0
printed two times, 1
printed four times, 2
printed 8 times, and hi
printed 8 times.
- Yes, it's correct. (see below)
- No,
i++
is executed after the call offork
, because that's the way thefor
loop works. - If all goes successfully, yes. However, remember that
fork
may fail.
A little explanation on the second one:
for (i = 0;i < 3; i++)
{
fork();
}
is similar to:
i = 0;
while (i < 3)
{
fork();
i++;
}
So i
in the forked processes(both parent and child) is the value before increment. However, the increment is executed immediately after fork()
, so in my opinion, the diagram could be treat as correct.