Using c language to implement HUP signal restart process method

  • 2020-04-02 00:43:30
  • OfStack

The code is as follows:

#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] try to use absolute paths because chdir() may be used during program execution.
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: %sn", bak_argv[0], strerror(errno));
 closelog();

 exit(EXIT_FAILURE);
}


Related articles: