孤儿进程:
当父进程不等待子进程退出,在子进程退出前就结束了生命,此时子进程就变成了孤儿进程。在linux系统中为了避免孤儿进程,init(pid=1)专门收留孤儿进程,变成孤儿进程的父进程。
代码实现如下:
1 #include <sys/types.h>
2 #include <unistd.h>
3 #include<stdio.h>
4 #include<stdlib.h>
5 /*孤儿进程*/
6 int main()
7 {
8 pid_t pid;
9 int i=0;
10 int stast=10;//**
11 pid=fork();//调用vfork()函数
12 if(pid>0)
13 { //父进程运行一次就退出。
14 printf("The father process id running ! fatherpid=%d \n",getpid());
15 }
16 if(pid==0)
17 {
18
19 while(1)
20 {
21 //打印子进程进程号信息。
22 printf("The child process is running ! childpid=%d fatherpid=%d \n",getpid(),getppid());
23 sleep(2);
24 i++;
25 if(i==5)
26 {
27 //当子进程运行5 次就退出
28 printf("The child process will be exit !\n");
29 exit(0);//**
30 }
31 }
32 }
33 return 0;
34 }
运行程序:
@Embed_Learn:~$ ./a.out
The father process id running ! fatherpid=4868
The child process is running ! childpid=4869 fatherpid=1
CLC@Embed_Learn:~$ The child process is running ! childpid=4869 fatherpid=1
The child process is running ! childpid=4869 fatherpid=1
The child process is running ! childpid=4869 fatherpid=1
The child process is running ! childpid=4869 fatherpid=1
The child process will be exit !
从打印到的信息可以看到,父进程没有退出时(子进程并没有退出),父进程的pid=4868.退出后父进程的pid=1.说明init收留了子进程。