代码如下所示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <syslog.h>
#include <stdarg.h>
char **bak_argv;
int flag = 0;
void restart(void);
void sighup_handler(int sig);
// argv[0] 尽量使用绝对路径, 因为程序执行过程中可能会使用 chdir() .
int main(int argc, char *argv[])
{
openlog("sig_hup", LOG_PID, 0);
syslog(LOG_ERR, "%s", argv[0]);
closelog();
bak_argv = argv;
signal(SIGHUP, sighup_handler);
while(1)
{
if(flag)
restart();
sleep(10);
}
return 0;
}
void sighup_handler(int sig)
{
flag = 1;
}
void restart(void)
{
switch(fork())
{
case -1:
openlog("sig_hup", LOG_PID, 0);
syslog(LOG_ERR, "fork failed: %s", strerror(errno));
closelog();
exit(EXIT_FAILURE);
break;
case 0:
break;
default:
exit(EXIT_SUCCESS);
}
execv(bak_argv[0], bak_argv);
openlog("sig_hup", LOG_PID, 0);
syslog(LOG_ERR, "execv(%s, ...) failed: %s\n", bak_argv[0], strerror(errno));
closelog();
exit(EXIT_FAILURE);
}