title: C Binary Tree fork depth and width
body: <p>I'm learning C and I'm stuck with fork function and processes. I want to create a c program that gets 2 inputs (depth and width) to create the tree like in the <a href="https://i.stack.imgur.com/yNyS5.jpg" rel="nofollow noreferrer">image</a></p>
  <p>This is the code I have done now:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  #include&lt;sys/wait.h&gt;
  
  int
  main (int argc, char *argv[])
  {
    int i, depth, width, pid, j, pid2;
  
    if (argc != 3)
      exit (0);
  
    depth= atoi (argv[1]);
    width = atoi (argv[2]);
  
    for (i = 0; i &lt; width; i++)
      {
        pid = fork ();
        if (pid &lt; 0)
          {
            printf (&quot;Error&quot;);
            exit (1);
          }
            else if (pid == 0)
          {
            for (j = 0; j &lt; depth; j++)
              {
                pid2 = fork ();
                if (pid2 &lt; 0)
                  {
                    printf (&quot;Error&quot;);
                    exit (1);
                  }
                    else if (pid2 == 0)
                  {
                    printf (&quot;Child (%d): %d\n&quot;, j + 1, getpid ());
                    exit (0);
                  }
                    else
                  {
                    wait (NULL);
                  }
              }
          }
            else
          {
            wait (NULL);
          }
      }
  
    printf (&quot;Child %d and parent %d\n&quot;, getpid (), getppid ());
    sleep (1);
    return 0;
  }
  </code></pre>