避免僵尸进程的三种方法

一、让僵尸进程的父进程来回收,父进程每隔一段时间来查询子进程是否结束并回收,调用wait()或者waitpid(),通知内核释放僵尸进程

/*
让僵尸进程的父进程来回收,父进程每隔一段时间来查询子进程是否结束并回收,
调用wait()或者waitpid(),通知内核释放僵尸进程
*/

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(void)
{
	pid_t pid=fork();
	int n=0;
	char *s=NULL;
	if(pid<0){
		perror("fork creat ");
	}else if(pid>0){//父进程
		n=1;
		s="this is parent process";
	}else{//pid=0//子进程
		n=10;
		s="this is child process";
	}
	for(int i=0;i<n;++i){
		printf("%s\n",s);
		if(pid>0){	
			printf("i am waiting for you ,my child\n");
			wait(NULL);	
		}
		sleep(1);
	}
	printf("%s bye\n",s);
	return 0;
}
运行结果

xfliu@ubuntu:避免僵尸进程$ ./bin/1
this is parent process
i am waiting for you ,my child
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process bye
this is parent process bye

二、
采用信号SIGCHLD通知处理,并在信号处理程序中调用wait函数

/*
采用信号SIGCHLD通知处理,并在信号处理程序中调用wait函数
*/

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/wait.h>
#include <signal.h>
void signal_wait(int isig)
{
	wait(NULL);
	printf("child is cleaned\n");
}
int main(void)
{
	pid_t pid=fork();
	char *s=NULL;
	if(signal(SIGCHLD,signal_wait)==SIG_ERR){
		perror("install signal_wait");
	}
	if(pid<0){
		perror("fork creat ");
	}else if(pid>0){//父进程
		sleep(1);
		s="this is parent process";
	}else{//pid=0//子进程
		s="this is child process";
	}
	printf("%s bye\n",s);
	return 0;
}

结果

this is child process bye
child is cleaned
this is parent process bye
xfliu@ubuntu:避免僵尸进程$ 


三、让僵尸进程变成孤儿进程,由init回收,就是让父亲先死


#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(void)
{
	pid_t pid=fork();
	int n=0;
	char *s=NULL;
	if(pid<0){
		perror("fork creat ");
	}else if(pid>0){//父进程
		n=1;
		s="this is parent process";
	}else{//pid=0//子进程
		n=10;
		s="this is child process";
	}
	for(int i=0;i<n;++i){
		printf("%s\n",s);
		/*
		if(pid>0){	
			printf("i am waiting for you ,my child\n");
			wait(NULL);	
		}
		sleep(1);
		*/
	}
	printf("%s bye\n",s);
	return 0;
}

运行结果:

xfliu@ubuntu:避免僵尸进程$ ./bin/2
this is parent process
this is parent process bye
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process
this is child process bye

关于wait与waitpid以后再研究

  • 15
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值