如何仅使用特定的 child 进行分叉?

How to fork only with a specific child?

我正在尝试构建这样的进程树:

               P1
            /      \
          P3        P2
                      \
                       P4
                        \
                         ....

但我无法让它工作。我试过了,但它只与 P1 分叉。

for(int i = 0; i < depth; i++) {
    int _pid = fork();
    if(_pid == 0) {
        printf("[son] pid %d from [parent] pid %d\n", getpid(), getppid());
        exit(0);
    }
}
wait(NULL);

仅使用一个 fork 调用的要求使解决方案既麻烦又丑陋,但仍然可以像这样实现:

第 1 步:创建一个内部循环,如果 i 为 0,它将 运行 两次,对于任何 i > 0.

一次。

第 2 步:仅在外循环的第一次迭代后在子进程中进行 fork。

第 3 步:退出在内循环的第二次迭代中分叉的子级。

int cur_pid = 0;

printf("Root PID %d started by %d\n", getpid(), getppid());

for (int i = 0; i < depth && cur_pid == 0; i++) {
    for (int j = 0; j < (i ? 1 : 2); j++) {
        cur_pid = fork();
        if (cur_pid == 0) {
            printf("[son] pid %d from [parent] pid %d\n", getpid(), getppid());
            if (j == 1) {
                exit(0);
            } else {
                break;
            }
        } else if (cur_pid < 0) {
            printf("Error forking at PID %d\n", getpid());
        }
    }
}

wait(NULL);

如果你想要 getppid 到 return 有效值,请记住在每次迭代的子进程上 wait