1. 程式人生 > >避免殭屍程序的三種方法

避免殭屍程序的三種方法

一、讓殭屍程序的父程序來回收,父程序每隔一段時間來查詢子程序是否結束並回收,呼叫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以後再研究