避免僵尸进程的三种方法

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

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

#include
#include
#include
#include
#include
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;i0){	
			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
#include
#include
#include
#include
#include 
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
#include
#include
#include
#include
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;i0){	
			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
避免僵尸进程的三种方法_第1张图片 避免僵尸进程的三种方法_第2张图片 避免僵尸进程的三种方法_第3张图片

关于wait与waitpid以后再研究

你可能感兴趣的:(LSD学习笔记)