父进程创建子进程后, 父进程先挂了, 于是子进程成了孤儿进程, 被新的init进程所领养。
来看代码:
#include <stdio.h>
#include <unistd.h>
int main()
{
int pid = 0;
pid = fork();
if(pid < 0)
{
printf("error1\n");
return 1;
}
if (0 == pid)
{
while(1);
return 0;
}
if (0 != pid)
{
while(1);
return 0;
}
return 0;
}
运行一下, 并在另外一个窗口观察a.out进程, 并杀死父进程, 然后再观察:
xxxxxx:~> ps -ef | grep a.out
1000 25493 24571 99 08:20 pts/2 00:00:13 ./a.out
1000 25494 25493 99 08:20 pts/2 00:00:13 ./a.out
1000 25496 24683 0 08:20 pts/6 00:00:00 grep a.out
xxxxxx:~> kill 25493
xxxxxx:~> ps -ef | grep a.out
1000 25494 1 98 08:20 pts/2 00:00:54 ./a.out
1000 25552 24683 0 08:21 pts/6 00:00:00 grep a.out
可以看到, init(进程号为1)成了继父。
孤儿进程就这么简单。