捕获指定的信号来重启进程: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);
}