title: C Processes fork()
body: <p>I am exploring parent process &amp; child processes concept in UNIX. I wrote this small code thinking that x no. or processes would get created. But it has created a different number - </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  
  int main(int argv, char *argc[])
  {
      int i;
      pid_t childpid;
  
      for(i=0; i&lt;3; i++)
      {
          childpid = fork();
          if(childpid == -1)
          {
              perror("Failed to Fork");
              return 1;
          }
  
          if(childpid == 0)
              printf("You are in Child: %ld\n", (long)getpid());
          else
              printf("You are in Parent: %ld\n", (long)getpid());
      }
      return 0;
  }
  
  OUTPUT:
  You are in Parent: 30410
  You are in Child: 30411
  You are in Parent: 30410
  You are in Child: 30412
  You are in Parent: 30411
  You are in Parent: 30410
  You are in Child: 30413
  You are in Child: 30414
  You are in Parent: 30412
  You are in Parent: 30411
  You are in Child: 30415
  You are in Child: 30416
  You are in Parent: 30413
  You are in Child: 30417
  </code></pre>
  
  <p>I understand that in a <code>fork()</code> situation a parent or a child might get preference in execution. That's is not bothering me, what's bothering me is the number of processes that are getting executed. Why is it 14? and not some 2^n number which is what would happen if we are executing <code>fork(); fork(); fork()</code> i.e. fork's one after the other.</p>
  
  <p>What am I missing?</p>
  
  <p><strong>UPDATE:</strong> One more clarification -</p>
  
  <blockquote>
    <p>The <code>fork</code> function copies the parent
    memory image so that the new process
    receives a copy of the address space
    of the parent.</p>
  </blockquote>
  
  <p>What does this mean? Does it mean - </p>
  
  <ol>
  <li>the child process starts executing after the <code>fork()</code> statement?</li>
  <li>the child process gets a copy of the parent process variables? so if <code>x=3</code> above fork, will the child process see this x as 3?</li>
  </ol>