#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork();
printf("pid : %d\n", getpid());
if( pid == 0)
{
printf("child: pid : %d \n", getpid());
while(1);
}
else
{
printf("parent: pid : %d \n", getpid());
//while(1);
}
}
在上面的 if
语句中的代码片段中,如果我们放入 while(1)
,它不会保持阻塞状态,当按下回车键时,程序会退出,但是如果我们输入 while(1)
,父级将保持阻塞状态,直到我们按下 ctrl+c。请澄清 child 的这种行为。
最佳答案
In the above code snippet inside if statement if we put while(1), it doesn't remains blocked
子进程实际上并没有退出;它只是变成了 orphan process因为它的 parent 退出了。孤立的 chuld 进程将被系统的 init 进程采用。您可以通过 ps
命令查看它。
但是如果您将 while(1);
放在父进程中,它会保持阻塞状态。
基本上,无论哪个进程有 while(1);
无限循环,它仍在运行。当 parent 退出时,您会得到提示并且 child 成为孤儿。但是子进程还在运行。
一般来说,你需要wait(2)
为父进程中的子进程收获子进程。
关于c - fork:子进程不会停留在无限循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47711423/