title: Unpredictable output in simple fork program
body: <p>Pardon me community for asking such a silly question - I've already spent 5+ hours trying to figure out reason but I've failed.</p>
  <p>Below is the code, it was a question on our exam - we were asked if we can predict the output of this code and will it be definite?</p>
  <p>After running this code on several machines, I've observed that output everywhere is - &quot; child parent&quot; .</p>
  <p>My understanding of below code is that once the process has forked, a copy of process will be created which can only execute the statements which are written below the fork() call only. Now once fork() is done, there will be two processes - a child process &amp; parent process . ( we've been instructed in our school that first parent process terminates and then child process when we are using pipes, however on searching internet I can only see that it cannot be decided which runs first.</p>
  <p>Here is what I think should happen -</p>
  <h1>Scenario 1 - Child executes first</h1>
  <p>I think that when child executes first, it will first print &quot;child&quot;, then write to file descriptor and then child process terminates due to _exit(0) and then parent process proceeds, reads and prints Parent. This is what is happening. I don't know whether this is actually happening or not.</p>
  <h1>Scenario 2 : Parent is executed first,</h1>
  <p>now it's attempting to first read empty pipe. Parent will try to read data, get blocked, then child will first print child, then write to pipe, which will enable read command and hence parent will be printed after it.</p>
  <p>Can someone confirm if my understanding is correct and point out mistakes in my understanding..</p>
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;unistd.h&gt;
  #include&lt;sys/wait.h&gt;
  int BUFSIZE = 4096;
  int main (int argc, char* argv[])
   {   int fd[2];
       pid_t pid;
       char buffer[BUFSIZE];
       pipe(fd);
       if ((pid = fork()) == 0)
      {   printf(&quot;child\n&quot;);
      write(fd[1], &quot;a&quot;, 1);
       _exit(0);
       }
      read(fd[0], buffer, BUFSIZE);
      printf(&quot;parent\n&quot;);
       }
  </code></pre>