title: How do 2 or more fork system calls work?
body: <p>Here's a code where I use 2 fork() system calls one after another - 
  How does it actually work?</p>
  
  <pre><code> #include &lt;unistd.h&gt;
   #include &lt;iostream.h&gt;
   using namespace std;
  
   int main()
   {
      cout &lt;&lt; "0. I am process " &lt;&lt; getpid() &lt;&lt; endl;
      (void) fork();
      cout &lt;&lt; "1. I am process " &lt;&lt; getpid() &lt;&lt; endl;
      (void) fork();
      cout &lt;&lt; "2. I am process " &lt;&lt; getpid() &lt;&lt; endl;
  }
  </code></pre>
  
  <p>I get the output as :  <br/>
  0. I am process 27701 <br/>
  1. I am process 25915 <br/>
  1. I am process 27701 <br/>
  2. I am process 27781 <br/>
  2. I am process 26170 <br/>
  2. I am process 27701 <br/></p>
  
  <p><strong>This is the next program where I've used 3 fork system calls, how do I get such an output? If I were to solve this code manually, what would be the logic?</strong></p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;iostream&gt;
  using namespace std;
  
  int main()
  {
      cout &lt;&lt; "0. I am process " &lt;&lt; getpid() &lt;&lt; endl;
      (void) fork();
      cout &lt;&lt; "1. I am process " &lt;&lt; getpid() &lt;&lt; endl;
      (void) fork();
      cout &lt;&lt; "2. I am process " &lt;&lt; getpid() &lt;&lt; endl;
      (void) fork();
      cout &lt;&lt; "3. I am process " &lt;&lt; getpid() &lt;&lt; endl;
  }
  </code></pre>
  
  <p>Here I get the output as :  <br/>
  0. I am process 27116  <br/>
  1. I am process 26147  <br/>
  2. I am process 27371  <br/>
  2. I am process 26147  <br/>
  3. I am process 24416  <br/>
  3. I am process 27371  <br/>
  3. I am process 27508  <br/>
  3. I am process 26147  <br/>
  1. I am process 27116  <br/>
  2. I am process 21406  <br/>
  2. I am process 27116  <br/>
  3. I am process 27369  <br/>
  3. I am process 21406  <br/>
  3. I am process 26752  <br/>
  3. I am process 27116  <br/></p>