Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a process tree

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?

like image 492
cristid9 Avatar asked Mar 31 '26 08:03

cristid9


1 Answers

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.

like image 159
alk Avatar answered Apr 02 '26 20:04

alk