c - Visually what happens to fork() in a For Loop -
i have been trying understand fork() behavior. time in for-loop. observe following code:
#include <stdio.h> void main() { int i; (i=0;i<3;i++) { fork(); // printf statement debugging purposes // getppid(): gets parent process-id // getpid(): child process-id printf("[%d] [%d] i=%d\n", getppid(), getpid(), i); } printf("[%d] [%d] hi\n", getppid(), getpid()); } here output:
[6909][6936] i=0 [6909][6936] i=1 [6936][6938] i=1 [6909][6936] i=2 [6909][6936] hi [6936][6938] i=2 [6936][6938] hi [6938][6940] i=2 [6938][6940] hi [1][6937] i=0 [1][6939] i=2 [1][6939] hi [1][6937] i=1 [6937][6941] i=1 [1][6937] i=2 [1][6937] hi [6937][6941] i=2 [6937][6941] hi [6937][6942] i=2 [6937][6942] hi [1][6943] i=2 [1][6943] hi i visual person, , way me understand things diagramming. instructor said there 8 hi statements. wrote , ran code, , indeed there 8 hi statements. didn’t understand it. drew following diagram:

diagram updated reflect comments :)
observations:
- parent process (main) must iterate loop 3 times. printf called
- on each iteration of parent for-loop fork() called
- after each fork() call, incremented, , every child starts for-loop before incremented
- at end of each for-loop, "hi" printed
here questions:
- is diagram correct?
- why there two instances of
i=0in output? - what value of
icarried on each child after fork()? if same value oficarried over, when "forking" stop? - is case
2^n - 1way count number of children forked? so, heren=3, means2^3 - 1 = 8 - 1 = 7children, correct?
here's how understand it, starting @ for loop.
loop starts in parent,
i == 0parent
fork()s, creating child 1.you have 2 processes. both print
i=0.loop restarts in both processes,
i == 1.parent , child 1
fork(), creating children 2 , 3.you have 4 processes. 4 print
i=1.loop restarts in 4 processes,
i == 2.parent , children 1 through 3
fork(), creating children 4 through 7.you have 8 processes. 8 print
i=2.loop restarts in 8 processes,
i == 3.loop terminates in 8 processes,
i < 3no longer true.all 8 processes print
hi.all 8 processes terminate.
so 0 printed 2 times, 1 printed 4 times, 2 printed 8 times, , hi printed 8 times.
wiki
Comments
Post a Comment