简体   繁体   中英

C Binary Tree fork depth and width

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 image

This is the code I have done now:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<sys/wait.h>

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 < width; i++)
    {
      pid = fork ();
      if (pid < 0)
        {
          printf ("Error");
          exit (1);
        }
          else if (pid == 0)
        {
          for (j = 0; j < depth; j++)
            {
              pid2 = fork ();
              if (pid2 < 0)
                {
                  printf ("Error");
                  exit (1);
                }
                  else if (pid2 == 0)
                {
                  printf ("Child (%d): %d\n", j + 1, getpid ());
                  exit (0);
                }
                  else
                {
                  wait (NULL);
                }
            }
        }
          else
        {
          wait (NULL);
        }
    }

  printf ("Child %d and parent %d\n", getpid (), getppid ());
  sleep (1);
  return 0;
}

First of all, you are misunderstanding the meaning of "width" and "depth" for a tree - your picture does not represent a tree of width 2 and depth 3. Your picture shows only a part of a tree of width 2, not the whole tree; and, in your picture the depth of the tree is 2, not 3. Grok this stuff first.

After you understand trees, you are ready to implement one with a single process (forget fork for now).

You can't implement a tree with 2 nested loops, one for width, one for depth. You can use a for loop for width, but you have to use recursion for the depth. The recursive function has depth as parameter, and when you call it again, you increment the parameter.

OK, once you figure that out, then add forking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM