title: Visually what happens to fork() in a For Loop
body: <p>I have been trying to understand <a href="http://en.wikipedia.org/wiki/Fork_(system_call)" rel="noreferrer"><code>fork()</code></a> behavior. This time in a <code>for-loop</code>. Observe the following code: </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  void main()
  {
     int i;
  
     for (i=0;i&lt;3;i++)
     {
        fork();
  
        // This printf statement is for debugging purposes
        // getppid(): gets the parent process-id
        // getpid(): get child process-id
  
        printf("[%d] [%d] i=%d\n", getppid(), getpid(), i);
     }
  
     printf("[%d] [%d] hi\n", getppid(), getpid());
  }
  </code></pre>
  
  <p><em>Here is the output:</em></p>
  
  <pre><code>[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
  </code></pre>
  
  <p>I am a very visual person, and so the only way for me to truly understand things is by diagramming. My instructor said there would be 8 <em>hi</em> statements. I wrote and ran the code, and indeed there were 8 <em>hi</em> statements. But I really didn’t understand it. So I drew the following diagram:</p>
  
  <p><img src="https://i.stack.imgur.com/x7JPT.png" alt="enter image description here"></p>
  
  <p><em>Diagram updated to reflect comments :)</em></p>
  
  <h2>Observations:</h2>
  
  <ol>
  <li>Parent process (main) must iterate the loop 3 times. Then printf is called</li>
  <li>On each iteration of parent for-loop a fork() is called</li>
  <li>After each fork() call, i is incremented, and so every child starts a for-loop from i before it is incremented</li>
  <li>At the end of each for-loop, "hi" is printed</li>
  </ol>
  
  <h2>Here are my questions:</h2>
  
  <ul>
  <li><em>Is my diagram correct?</em></li>
  <li><strong>Why are there <em>two</em> instances of <code>i=0</code> in the output?</strong> </li>
  <li>What value of <code>i</code> is carried over to each child after the fork()? If the same value of <code>i</code> is carried over, then when does the "forking" stop? </li>
  <li>Is it always the case that <code>2^n - 1</code> would be a way to count the number of children that are forked? So, here <code>n=3</code>, which means <code>2^3 - 1 = 8 - 1 = 7</code> children, which is correct?</li>
  </ul>