unix高级编程-僵尸进程和孤儿进程

僵尸进程: 一个父进程利用fork创建子进程,如果子进程退出,而父进程没有利用wait 或者 waitpid 来获取子进程的状态信息,那么子进程的状态描述符依然保存在系统中。

孤儿进程:一个父进程退出, 而它的一个或几个子进程仍然还在运行,那么这些子进程就会变成孤儿进程,孤儿进程将被init进程(进程号为1)所收养,并由init进程对它们完成状态收集的工作

僵尸进程不为子进程“收尸”

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
pid_t cid;
//child pid
printf("Before fork Process id:%d\n", getpid());
cid = fork();
if (cid == 0){
printf("Child process id (my parent pid is %d):%d\n", getppid(),getpid());
for(int i = 0; i < 3; i++){
printf("hello\n");
}
}else{
printf("Parent Process id: %d\n",getpid());
for(int i = 0; i < 1; i++){
printf("world(%d)\n",getppid());
sleep(100);
}
//wait(NULL); //等待子进程结束,再返回,()里面参数一般是空指针
}
return 0;
}

在这里插入图片描述
13591僵尸进程在这里插入图片描述
避免僵尸进程
除了我们知道用wail函数等待,也就是前面注释的那个wait函数
我们还可以发送一个信号让程序帮我们回收产生的子进程
我们看下linux所支持的信号
在这里插入图片描述signal(SIGCHLD,SIG_IGN);代表子进程死亡不给父进程发信号(ignore),也就是父进程创建子进程不给他“收尸”,那么系统会帮他“收尸”

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
pid_t cid;
//child pid
signal(SIGCHLD,SIG_IGN);
printf("Before fork Process id:%d\n", getpid());
cid = fork();
if (cid == 0){
printf("Child process id (my parent pid is %d):%d\n", getppid(),getpid());
for(int i = 0; i < 3; i++){
printf("hello\n");
}
}else{
printf("Parent Process id: %d\n",getpid());
for(int i = 0; i < 1; i++){
printf("world(%d)\n",getppid());
sleep(100);
}
//wait(NULL); //等待子进程结束,再返回,()里面参数一般是空指针
}
return 0;
}

我们可以看到这里并没有僵尸进程了
在这里插入图片描述

大家可以尝试改写我的代码,自己写一个孤儿进程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白帽小丑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值