fion_
fion_

Reputation: 57

Finding the level of a child process in a process tree

I've been trying to create a process tree using fork() and print each child's level (0 for base process, 1 for its child, 2 for its grandchild etc.) in the tree. The code below only works for depth 0 and 1. Any idea how I can improve it? Thanks.

#include <stdio.h>
#include <unistd.h>
int i;
int main()
{
    pid_t baseID = getpid();
    printf("Base Process ID: %d, level: 0 \n", baseID);
    for (i = 0; i < 3; i++) {
        int level = 1;
        pid_t pid;
        pid = fork();
        if (pid == 0) {
            pid_t childID = getpid();
            pid_t parentID = getppid();
            if (parentID == baseID) {
                level = 1;
            }
            else {
                // do something for grandchildren here
                level++;
            }
            printf("Process ID: %d, Parent ID: %d, level: %d \n", getpid(), getppid(), level);
        }
        else {
            wait(NULL);
        }
    }
    return 0;
}

Upvotes: 1

Views: 1609

Answers (1)

aminosbh
aminosbh

Reputation: 193

The intended process tree is the following:

0
|->1
|  |->2
|  |  |->3
|  |
|  |->2
|
|->1
|  |->2
|
|->1

So to be able to print the level of each process, we should just initialize the level variable to 0 outside the main for loop and just increment its value each time a child process is created.

The following code will print the level of each child process as expected:

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

int main()
{
  pid_t baseID = getpid();
  printf("Base Process ID: %d, level: 0 \n", baseID);

  int level = 0;

  for (int i = 0; i < 3; i++) {

    pid_t pid = fork();

    if (pid == 0) { // Child

      pid_t childID = getpid();
      pid_t parentID = getppid();

      level++;

      printf("Process ID: %d, Parent ID: %d, level: %d \n", getpid(), getppid(), level);

    } else { // Parent
      wait(NULL);
    }
  }

  return 0;
}

Upvotes: 1

Related Questions