编程模拟孤儿进程

孤儿进程:

当父进程不等待子进程退出,在子进程退出前就结束了生命,此时子进程就变成了孤儿进程。在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收留了子进程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值