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:

enter image description here

diagram updated reflect comments :)

observations:

  1. parent process (main) must iterate loop 3 times. printf called
  2. on each iteration of parent for-loop fork() called
  3. after each fork() call, incremented, , every child starts for-loop before incremented
  4. at end of each for-loop, "hi" printed

here questions:

  • is diagram correct?
  • why there two instances of i=0 in output?
  • what value of i carried on each child after fork()? if same value of i carried over, when "forking" stop?
  • is case 2^n - 1 way count number of children forked? so, here n=3, means 2^3 - 1 = 8 - 1 = 7 children, correct?

here's how understand it, starting @ for loop.

  1. loop starts in parent, i == 0

  2. parent fork()s, creating child 1.

  3. you have 2 processes. both print i=0.

  4. loop restarts in both processes, i == 1.

  5. parent , child 1 fork(), creating children 2 , 3.

  6. you have 4 processes. 4 print i=1.

  7. loop restarts in 4 processes, i == 2.

  8. parent , children 1 through 3 fork(), creating children 4 through 7.

  9. you have 8 processes. 8 print i=2.

  10. loop restarts in 8 processes, i == 3.

  11. loop terminates in 8 processes, i < 3 no longer true.

  12. all 8 processes print hi.

  13. all 8 processes terminate.

so 0 printed 2 times, 1 printed 4 times, 2 printed 8 times, , hi printed 8 times.





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -