Dipesh Desai
Dipesh Desai

Reputation: 114

Process Tree Hierarchy in C

I am trying to create a process tree hierarchy that creates C children for a tree height H. I have written the following code, but it creates only one child per process. Where am I going wrong?

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

void createProcess(int height,int children){
    int root, parent, t1, t2, t3, i, pid, status; 

    root = getpid();
    parent = getppid();
    printf("%d: Process starting\n", root);
    printf("%d: Parent's id = %d\n", root, parent);
    printf("%d: Height in the tree = %d\n", root, height);
    printf("%d: Creating %d children at height %d\n", root, children, height - 1);

    char c[4], h[4];
    sprintf(h, "%d", height - 1);
    sprintf(c, "%d", children);

    char *args[] = {"./forkk", h, c, NULL}; 
    for (i = 0; i < children; i++) {
        t1 = fork();
        if (t1 != 0) {
            printf("child pid %d    parent pid %d\n", getpid(), getppid());
            break;
        }
        if (t1 == 0) {
            execvp("./forkk", args);
        }
    }
    pid = wait(&status);
    sleep(5);
    //printf("%d Terminating at Height %d\n",root,height);
}

int main(int argc, char** argv) {
    int i;

    printf("No of Arguments: %d\n", argc);
    for (i = 0; i < argc; i++) {
        printf("%s\n", argv[i]);
    }
    int height = atoi(argv[1]);
    int children = atoi(argv[2]);
    printf("Height  %d\n", height);
    printf("Children  %d\n", children);
    if (height > 1)
        createProcess(height, children);
    return 0;
}

Upvotes: 1

Views: 1221

Answers (1)

bca
bca

Reputation: 474

It's because you have break in the for loop. In if (t1 != 0). Parent exits loop after creating first child.

And @John Bollinger is right, that is terrible way to do that. What you're doing is recursively calling main function. You should and you can handle this problem in createProcess.

Upvotes: 1

Related Questions