加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

【转】Linux杀死fork产生的子进程的僵尸进程defunct

发布时间:2020-12-13 22:02:29 所属栏目:Linux 来源:网络整理
导读:僵尸进程 就是 已经结束,但是还没有清理出去的.用kill -9 $PID 也无法杀死. 所以程序中应该避免出现僵尸进程. 用fork之后,父进程如果没有wait /waitpid 等待子进程的话,子进程完毕后,就成了僵尸进程. 但是父进程如果等待wait/waitpid的话,就没法干别的事情了

僵尸进程 就是 已经结束,但是还没有清理出去的.用kill -9 $PID 也无法杀死.

所以程序中应该避免出现僵尸进程.

用fork之后,父进程如果没有wait /waitpid 等待子进程的话,子进程完毕后,就成了僵尸进程.

但是父进程如果等待wait/waitpid的话,就没法干别的事情了...尤其在多个子进程的情况下.所以 中断 信号量 是一个好办法:

复制代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

void sig_child(){
pid_t pid;
int status;
while((pid = waitpid(-1,&status,WNOHANG)) > 0) {}
//Key !!!!!!!! wait or waitpid
return;
}
void nodefunct_sig(){
signal(SIGCHLD,sig_child);//prevent defunct

int child=0;
pid_t status=0;
int i=0;
while(1){
if(child=fork()==0){
childf();
printf("child(%d):I will be exit...pgid=%dn",getpid(),getpgid(getpid()));//getpgrp()
abort();
char cmd[1024]="";
sprintf(cmd,"kill -9 %d",getpid());
system(cmd);
exit(5);
}else{
printf("Parent(%d):Main process...n",getpid());
//kill(child,SIGABRT);
system("ps -A|grep a.out");

sleep(3);
}
printf("Parent: waitting child...pgid=%dnn",getpgid(getpid()));
//waitpid(child,
}
}
void main(){
nodefunct_sig();
}

复制代码

?


参考自:http://topic.csdn.net/t/20020424/21/673887.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读