3

The following program should create processes tree of depth K with N children on each node.

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

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 < 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", &levelLimit, &children);

    spawnNodes(0, levelLimit, children, 0, 0);

    return 0;
}

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.

This is what I mean:

p1--p2---p3--exit(0)
     \---p4--exit(0)
      \--p5--p6--exit(0)

I have discovered this while debugging in gdb. Also, this is the output for a binary tree of depth 2:

(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

What am I doing wrong?

alk
  • 69,737
  • 10
  • 105
  • 255
cristid9
  • 1,070
  • 1
  • 17
  • 37

1 Answers1

2

What am I doing wrong?

If you want to create N children to one process do not have the creating process wait() after having created the 1st child.


To better understand what is going on change this

if (curLevel == levelLimit)
  exit(0);

to be

if (curLevel == levelLimit) 
  pause(); 

This change will let each child live on until it explicitly gets killed. Doing so no call to wait() will return beforehand. This way you see that each parent creates exactly one child only.

alk
  • 69,737
  • 10
  • 105
  • 255
  • Now I've got an even stranger behavior. Take a look at this snippet: http://pastebin.com/uVmJS4gb. This is the output: http://pastebin.com/WfC1DeKK. Which is not a tree. Closer to a tree than the last version, but not a tree yet. – cristid9 May 15 '16 at 11:09