创建特定的流程树

时间:2017-11-06 18:45:38

标签: c fork

我尝试在image上创建流程树。下面是我的代码,我写的。它工作正常但只有一半。我的代码输出在second screenshot上。问题是,我不知道如何制作上一代。

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


int main() {
    int i;
    int j;

    pid_t ppid;
    pid_t cpid;
    ppid = getpid();
    printf("I'm the parent, my PID is: %d\n", ppid);
    for (i = 0; i < 4; i++) {
        ppid = fork();
        if (ppid == 0) {
            printf("Hello, my PID is: %d, my parent's PID is %d\n", getpid(), getppid());
            for(j = 0; j < 2; j++) {
                ppid = fork();
                if (ppid == 0) {
                    printf("Hello, my PID is: %d, my parent's PID is %d\n", getpid(), getppid());
                    sleep(60);
                    printf("I'm process %d and I'm done\n", getpid());
                    exit(0);
                }
            }
            sleep(60);
            printf("I'm process %d and I'm done\n", getpid());
            exit(0);
        }   
    }

    sleep(1);
    printf("I'm process %d. Waiting for one of my children to complete", getpid());
    wait(NULL);
    printf("Eltern: I'm done\n");
    printf("... and bye. \n");
}

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题是正确的,你只需要在最内层的if语句中添加fork

            if (ppid == 0) {
                printf("Hello, my PID is: %d, my parent's PID is %d\n", getpid(), getppid());

                // Add one more fork here

                sleep(60);
                printf("I'm process %d and I'm done\n", getpid());
                exit(0);
            }