title: C concurrency program output depends whether out to stdout or a file
body: <p>Friend sent me a program:</p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  
  void chain(int n, int current_nr) {
      printf("Running %d\n", current_nr);
  
      pid_t pid = fork();
  
      if (pid != 0) { //parent
          return; 
      }
      else { //child
          if (current_nr == n - 2) {
              return;
          }
          else {
              chain(n, current_nr + 1);
          }
      }
  }
  
  int main(void) {
      puts("Program started");
  
      chain(5, 0);
  
      wait(NULL);
  
      return 0;
  }
  </code></pre>
  
  <p>If program is executed as ./program then the output is:</p>
  
  <pre><code>Program started
  Running 0
  Running 1
  Running 2
  Running 3
  </code></pre>
  
  <p>But after executing as ./program > outputfile then the outputfile content is:</p>
  
  <pre><code>Program started
  Running 0
  Running 1
  Running 2
  Running 3
  Program started
  Running 0
  Running 1
  Running 2
  Running 3
  Program started
  Running 0
  Running 1
  Running 2
  Program started
  Running 0
  Running 1
  Program started
  Running 0
  </code></pre>
  
  <p>What is going on?</p>