您的位置:首页 > 其它

子进程终止父进程捕捉子进程退出信号

2012-05-17 23:01 253 查看
要想不产生僵尸进程还有另外一种办法:父进程调用sigaction将SIGCHLD的处理动作置为SIG_IGN,这样fork出来的子进程在终止时会自动清理掉,不会产生僵尸进程,也不会通知父进程。系统默认的忽略动作和用户用sigaction函数自定义的忽略通常是没有区别的,但这是一个特例。此方法对于Linux可用,但不保证在其它UNIX系统上都可用。请编写程序验证这样做不会产生僵尸进程。

这里就不使用sigaction,这种方式比较麻烦。所以使用signal函数这个函数也是封装的sigaction

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
pid_t p;
void sig_term(int sig){
int i = 0;
waitpid(p, &i, 0);
//这里取得的退出状态也为2
printf("%d\n",WEXITSTATUS(i));
}
int main(){
int i = 0, j = 0;
p = fork();
if (p<0) {
perror("fork error\n");
exit(1);
}
if (p>0) { //this is parent
for (; i<20; i++) {
sleep(1);
//接收子进程退出的信号
signal(SIGCHLD, sig_term);
printf("this is parent\n");
}
}else{      //this is child
for (; j<5; j++) {
sleep(1);
printf("this is child\n");
}
//子进程退出状态为2
exit(2);
}
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐