title: In fork() which will run first, parent or child?
body: <p>When the following code runs, I understand  the parent and child both will run <em>in parallel</em> immediately after fork() is called.    </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(void)
  {
      int pfds[2];
      char buf[30];
  
      pipe(pfds);
  
      if (!fork()) {
          printf(" CHILD: writing to the pipe\n");
          write(pfds[1], "test", 5);
          printf(" CHILD: exiting\n");
          exit(0);
      } else {
          printf("PARENT: reading from pipe\n");
          read(pfds[0], buf, 5);
          printf("PARENT: read \"%s\"\n", buf);
          wait(NULL);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>That means child will execute:</p>
  
  <pre><code>printf(" CHILD: writing to the pipe\n"); 
  </code></pre>
  
  <p>And the parent will execute </p>
  
  <pre><code>printf("PARENT: reading from pipe\n");
  </code></pre>
  
  <p><em>In parallel.</em>  </p>
  
  <p>For those not familiar with <code>C</code>, in <code>sh</code>:</p>
  
  <pre><code>$ sh -c 'echo CHILD &amp; echo PARENT; wait'
  PARENT
  CHILD
  </code></pre>
  
  <p>So I ran this code on a single core cpu and also on dual core, but I noticed that parent is always getting printed first. Since the two are in parallel, it is quite reasonable to expect random order. But it is not happening like that.  Why is it like that?</p>