title: Fork() function in C
body: <p>Below is an example of the Fork function in action. Below is also the output. My main question has to to do with the a fork is called how values are changed. So pid1,2 and 3 start off at 0 and get changed as the forks happen. Is this because each time a fork happens the values are copied to the child and the specific value gets changed in the parent? Basically how do values change with fork functions?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  
  int main() {
      pid_t pid1, pid2, pid3;
      pid1=0, pid2=0, pid3=0;
      pid1= fork(); /* A */
      if(pid1==0){
          pid2=fork(); /* B */
          pid3=fork(); /* C */
      } else {
          pid3=fork(); /* D */
          if(pid3==0) {
              pid2=fork(); /* E */
          }
          if((pid1 == 0)&amp;&amp;(pid2 == 0))
              printf("Level 1\n");
          if(pid1 !=0)
              printf("Level 2\n");
          if(pid2 !=0)
             printf("Level 3\n");
          if(pid3 !=0)
             printf("Level 4\n");
         return 0;
      }
  }
  </code></pre>
  
  <p>Then this is the execution. </p>
  
  <pre><code>----A----D--------- (pid1!=0, pid2==0(as initialized), pid3!=0, print "Level 2" and "Level 4")
      |    |
      |    +----E---- (pid1!=0, pid2!=0, pid3==0, print "Level 2" and "Level 3")
      |         |
      |         +---- (pid1!=0, pid2==0, pid3==0, print "Level 2")
      |
      +----B----C---- (pid1==0, pid2!=0, pid3!=0, print nothing)
           |    |
           |    +---- (pid1==0, pid2==0, pid3==0, print nothing)
           |
           +----C---- (pid1==0, pid2==0, pid3!=0, print nothing)
                |
                +---- (pid1==0, pid2==0, pid3==0, print nothing)
  </code></pre>
  
  <p>Ideally below is how I would like to see it explained as this way makes sense to me. The * are where my main confusion lies. When the child forks for example <code>pid1 = fork();</code> that creates a process with all the values of the parent, but does it then pass up a value like lets say 1 to the parents pid1? Meaning the child would have pid 1=0, pid2=0 and pid3=0 and the parent then as pid1=2 and pid2 and 3 equal to 0? <a href="https://i.stack.imgur.com/SKOS3.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/SKOS3.jpg" alt="enter image description here"></a></p>