title: Understanding C's fork() through a simple example
body: <pre><code>#include &lt;stdio.h&gt;
  int num = 0;
  int main(int argc, char*argv[]){
      int pid;
      pid = fork();
      printf("%d", num);  
      if(pid == 0){       /*child*/
          num = 1;
      }else if(pid &gt; 0){  /*parent*/
          num = 2;
      }
      printf("%d", num);
  }
  </code></pre>
  
  <p>I'm having trouble understanding why the possible outputs would be 
  0102 or 0012 or 0201 or 0021. </p>
  
  <p>Here is what I (think) it should be producing. It hits the first printf statement and no matter what child or parent gets executed first, num hasn't been modified so 0 first. THEN next is either 1 or 2, then the next process executes so starts with 0 again (copied from the parent) and then either a 1 or 2 again. So the possible outputs should be:</p>
  
  <p>0101 or
  0102 or
  0201 or
  0202</p>