title: Can someone please explain how this works?fork(),sleep()
body: <pre class="lang-c prettyprint-override"><code>#include &lt;sys/wait.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include&lt;stdlib.h&gt;
  
  int main(void)
  
  {
    pid_t pids[10];
    int i;
  
  for (i = 9; i &gt;= 0; --i) {
      pids[i] = fork();
      if (pids[i] == 0) {
          printf("Child%d\n",i);
          sleep(i+1);
          _exit(0);
      }
  }
  
  for (i = 9; i &gt;= 0; --i){
      printf("parent%d\n",i);
      waitpid(pids[i], NULL, 0);
      }
  return 0;
  }
  </code></pre>
  
  <p>What is happening here? How is <code>sleep()</code> getting executed in the <code>for</code> loop? When is it getting called? Here is the output:</p>
  
  <pre><code>parent9
  Child3
  Child4
  Child2
  Child5
  Child1
  Child6
  Child0
  Child7
  Child8
  Child9  //there is a pause here
  parent8
  parent7
  parent6
  parent5
  parent4
  parent3
  parent2
  parent1
  parent0
  </code></pre>
  
  <p>Please explain this output. I am not able to understand how it's working.
  Step by step analysis would be great.</p>