title: Creating a process tree
body: <p>The following program should create processes tree of depth <code>K</code> with <code>N</code> children on each node. </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  
  void spawnNodes(int curLevel, int levelLimit, int childrenNumber, 
                  int nodeNumber, int offset)
  {
      if (curLevel == levelLimit)
          exit(0);
  
      curLevel++;
      printf("(%d, %d) Pid: %d with parent %d\n", curLevel, nodeNumber, 
              getpid(), getppid());
  
      for (int i = 0; i &lt; childrenNumber; i++)
      {
          pid_t childPid = fork();
          if (childPid == -1)
          {
              perror("Couldn't create process");
              exit(1);
          }
  
          if (childPid == 0)
          {
              spawnNodes(curLevel, levelLimit, childrenNumber, offset + i, 
                         offset + i);
          }
          else
          {
              wait(NULL);
          }
      }
  }
  
  int main()
  {
      int levelLimit, children;
      scanf("%d %d", &amp;levelLimit, &amp;children);
  
      spawnNodes(0, levelLimit, children, 0, 0);
  
      return 0;
  }
  </code></pre>
  
  <p>At a first glance it may look correct. However, there is a strange behavior that I don't understand. The first son of the process 1 goes 1 level deeper at it's last son. </p>
  
  <p>This is what I mean:</p>
  
  <pre><code>p1--p2---p3--exit(0)
       \---p4--exit(0)
        \--p5--p6--exit(0)
  </code></pre>
  
  <p>I have discovered this while debugging in <code>gdb</code>. Also, this is the output for a binary tree of depth <code>2</code>:</p>
  
  <pre><code>(1, 0) Pid: 5562 with parent 2835
  (2, 0) Pid: 5563 with parent 5562
  (2, 1) Pid: 5566 with parent 5563
  (2, 1) Pid: 5569 with parent 5562
  </code></pre>
  
  <p>What am I doing wrong?</p>