信号的自启动进程

捕获指定的信号来重启进程:SIGILL,SIGBUS, SIGFPE,SIGSEGV,SIGUSR1,SIGABRT
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>


void child_process();

bool parent_process(pid_t child_pid, int& exit_code);

int iExitFlag = 0;

int main(int argc, char** argv)
{
	int exit_code=1;
	
	while(true)
	{
		pid_t pid = fork();
		if(-1 == pid)
		{
			fprintf(stderr, "fork error!\n");
			break;
		}
		else if(0 == pid)
		{
			child_process(argc, argv);
		}
		else if (!parent_process(pid, exit_code))
		{
			break;
		}
	}
	return exit_code;
}

bool parent_process(pid_t child_pid, int& exit_code)
{
	printf("parent process is %d, and its work process is %d\n", getpid(), child_pid);
	bool restart = false;
		
	while(true)
	{
		int status;
		int retval = waitpid(child_pid, &status, 0);
		if (retval == -1)
		{
			if (EINTR == errno)
			{
				continue;
			}
			else
			{
				printf("Wait %d error, errno: %s!\n", child_pid, strerror(errno));
			}
		}
		else if (WIFSTOPPED(status))
		{
			exit_code = WSTOPSIG(status);			
		}
		else if (WIFEXITED(status))
		{
			exit_code = WEXITSTATUS(status);			
		}
		else if (WIFSIGNALED(status))
		{
			int signo = WTERMSIG(status);			
			exit_code = signo;
			
			if ((SIGILL == signo)
				|| (SIGBUS == signo)
				|| (SIGFPE == signo)
				|| (SIGSEGV == signo)
				|| (SIGUSR1 == signo)
				|| (SIGABRT == signo))
			{
				restart = true;
				printf("Process %d will restart self for signal %s!\n", child_pid, strsignal(signo));

				usleep(20);
			}
		}
		else
		{
			printf("Process %d was exited, but unkonw error.\n", child_pid);
		}
		break;
	}
	return restart;
}

void sig_int(int signo)
{
	if (signo == SIGUSR1)
	{
		iExitFlag = 1;
	}	
}

void child_process(int argc, char**argv)
{
	int errcode = 0;
	sigset_t sigset;
	sigset_t old_sigset;
	
	int exit_signo = SIGUSR1;
	signal(SIGUSR1, sig_int);

	if (exit_signo > 0)
	{
		if (-1 == sigemptyset(&sigset))
		{
			printf("Initialized signal set error!\n");
			exit(1);
		}
		if (-1 == sigaddset(&sigset, exit_signo))
		{
			printf("add %s to signal set error!\n", strsignal(exit_signo));
			exit(1);
		}
		if (-1 == sigprocmask(SIG_BLOCK, &sigset, &old_sigset))
		{
			printf("Block sigset error!\n");
			exit(1); 
		}
	} 
	sigset_t emptyMask;
	sigemptyset(&emptyMask);
	
	while(iExitFlag == 0)
	{
		sigsuspend(&emptyMask);
	}	
	
	exit(errcode);
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值