我用C语言编写了这段代码。我创建了一个父进程,它有两个子进程,其中一个成为了僵尸进程。在一秒钟后,它退出,等待他的父进程也结束了。另一个子进程则变成孤儿进程,然后结束了。我的问题是,如果我将wait
改为waitpid
会发生什么。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid;
int status, value;
pid = fork();
if (pid > 0) { // Father
pid = fork();
if (pid > 0) { // Father
wait(&status);
value = WEXITSTATUS(status);
if (value == 2)
printf("Child 2");
else if (value == 3)
printf("Child 1");
} else if (pid == 0) { //Child 2 - Orphan
sleep(4);
exit(2);
} else {
exit(1);
}
} else if (pid == 0) { // Child 1 - Zombie
sleep(1);
exit(3);
} else {
printf("Error al ejecutar el fork");
exit(1);
}
return 0;
}
init
接管该进程,等待它,然后该进程消失。 - Barmarwaitpid()
等待的进程不会变成孤儿,因为你正在等待它。 - Barmar