00. 目录
01. 孤儿进程概述
父进程运行结束,但子进程还在运行的子进程就称为孤儿进程(Orphan Process)。孤儿进程最终会被 init 进程(进程号为 1 )所收养,并由 init 进程对它们完成状态收集工作。
孤儿进程是没有父进程的进程,为避免孤儿进程退出时无法释放所占用的资源而变为僵尸进程,进程号为 1 的 init 进程将会接受这些孤儿进程,这一过程也被称为“收养”。init 进程就好像是一个孤儿院,专门负责处理孤儿进程的善后工作。每当出现一个孤儿进程的时候,内核就把孤儿进程的父进程设置为 init ,而 init 进程会循环地 wait() 它的已经退出的子进程。这样,当一个孤儿进程凄凉地结束了其生命周期的时候,init 进程就会代表党和政府出面处理它的一切善后工作。因此孤儿进程并不会有什么危害。
注意:
在有些启动图形界面的系统中,有些收养孤儿进程的并不一定是1号进程。
02. 孤儿进程代码
孤儿进程代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
int i = 0;
pid_t pid = -1;
//孤儿进程
pid = fork();
if (-1 == pid)
{
perror("fork");
goto err0;
}
else if (0 == pid)
{
while(i < 10)
{
printf("I am child process %d --> %d\n", getpid(), i++);
sleep(2);
}
exit(0);
}
return 0;
err0:
return 1;
}
测试结果:
03. 附录
3.1 参考博客:【Linux系统编程】特殊进程之孤儿进程