【发布时间】:2020-05-09 18:46:23
【问题描述】:
我正在尝试创建一个进程树,如下所示: F \ |\1 \ | |\3 | \4 \2 F 和 1 将等待他们的孩子被终止。不知何故,所有的父母 pid 都被表示为 1。其次,我认为是“所有人的父亲”的过程 - F 似乎不是真正的父亲。 这是我的代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main (){
int status;
pid_t child_1;
child_1 = fork();
if(child_1 == 0){ //This is the child 1 process.
printf("child 1:%d, %d\n", getpid());
int returnStatus;
waitpid(child_1, &returnStatus, 0);
pid_t child_3 = fork();
if(child_3 == 0){ //This is the child 3 process.
printf("child 3:%d, %d\n", getpid());
printf("parent child 3:%d\n", getppid());
}
else if(child_3 > 0){ // This is the father of child 3.
pid_t child_4 = fork();
if(child_4 == 0){ //This is the child 4 process.
printf("child 4:%d, %d\n", getpid());
printf("parent child 4:%d\n", getppid());
}
}
}
else { // This is the father of all processes.
int returnStatus;
waitpid(child_1, &returnStatus, 0);
printf("FATHER OF THEM ALL:%d\n", getpid());
pid_t child_2 = fork();
if(child_2 == 0){ // This is the child 2 process.
printf("child 2:%d, %d\n", getpid());
}
}
return 0;
}
【问题讨论】:
-
对
printf()的调用以打印对getpid()的调用结果有两个格式说明符,但只有一个数据参数。建议删除第二个格式说明符。 -
关于:
else { // This is the father of all processes.对fork()的调用有三(3)种返回值 1)0 表示在父进程中。发布的代码无法检查 -
关于:
waitpid(child_1, &returnStatus, 0);该语句位于子进程中。进程不能等待自己。并且变量child_1包含0,因此,在这种情况下,它将返回一个-1,因为没有child_1 的孩子等待 -
关于:`pid_t child_2 = fork(); if(child_2 == 0){ // 这是子 2 进程。 printf("child 2:%d, %d\n", getpid());` 在所有子进程退出之前,父进程不需要退出。发布的代码没有这样做。在旧系统中,这将导致产生
zombies。在现代系统中,子进程(在 linux 中)附加到init进程。两种情况都不好,(虽然附在init上比变成僵尸要好得多