X-Git-Url: http://git.madism.org/?a=blobdiff_plain;f=common%2Fcommon.c;h=43b2bf22145c2b014b4f4c2bb4988c0733e37fe6;hb=e327d3786ba0371eaaff8e6ba0fe3fc39f095ae2;hp=758e869a7da225ff3e1a6493a633995ec24adcaf;hpb=bcd90daa5d3d303afe13832249fa20cad7303f8c;p=apps%2Fpfixtools.git diff --git a/common/common.c b/common/common.c index 758e869..43b2bf2 100644 --- a/common/common.c +++ b/common/common.c @@ -44,11 +44,16 @@ sig_atomic_t sigint = false; sig_atomic_t sighup = false; +bool daemon_process = true; +int log_level = LOG_INFO; +bool log_syslog = false; + static FILE *pidfile = NULL; void common_sighandler(int sig) { switch (sig) { + case SIGTERM: case SIGINT: sigint = true; return; @@ -58,12 +63,12 @@ void common_sighandler(int sig) return; default: - syslog(LOG_ERR, "Killed (got signal %d)...", sig); + err("Killed (got signal %d)...", sig); exit(-1); } } -static int setnonblock(int sock) +int setnonblock(int sock) { int res = fcntl(sock, F_GETFL); @@ -193,10 +198,13 @@ int daemon_detach(void) open("/dev/null", O_RDWR); pid = fork(); - if (pid < 0) + if (pid < 0) { return -1; - if (pid) + } + if (pid) { + daemon_process = false; exit(0); + } setsid(); return 0; @@ -229,20 +237,11 @@ int drop_privileges(const char *user, const char *group) int pidfile_open(const char *name) { - struct flock lock; - p_clear(&lock, 1); - lock.l_type = F_WRLCK; if (name) { pidfile = fopen(name, "w"); if (!pidfile) return -1; - if (fcntl(fileno(pidfile), F_SETLK, &lock) == -1) { - syslog(LOG_ERR, "program already started"); - fclose(pidfile); - pidfile = NULL; - return -1; - } - fprintf(pidfile, "%d\n", getpid()); + fprintf(pidfile, "%d\n", getpid()); return fflush(pidfile); } return 0; @@ -261,14 +260,12 @@ int pidfile_refresh(void) static void pidfile_close(void) { - struct flock lock; - p_clear(&lock, 1); - lock.l_type = F_UNLCK; if (pidfile) { - rewind(pidfile); - ftruncate(fileno(pidfile), 0); - fcntl(fileno(pidfile), F_SETLK, &lock); - fclose(pidfile); + if (daemon_process) { + rewind(pidfile); + ftruncate(fileno(pidfile), 0); + } + fclose(pidfile); pidfile = NULL; } } @@ -277,17 +274,17 @@ int common_setup(const char* pidfilename, bool unsafe, const char* runas_user, const char* runas_group, bool daemonize) { if (pidfile_open(pidfilename) < 0) { - syslog(LOG_CRIT, "unable to write pidfile %s", pidfilename); + crit("unable to write pidfile %s", pidfilename); return EXIT_FAILURE; } if (!unsafe && drop_privileges(runas_user, runas_group) < 0) { - syslog(LOG_CRIT, "unable to drop privileges"); + crit("unable to drop privileges"); return EXIT_FAILURE; } if (daemonize && daemon_detach() < 0) { - syslog(LOG_CRIT, "unable to fork"); + crit("unable to fork"); return EXIT_FAILURE; } @@ -300,9 +297,10 @@ extern exitcall_t __madexit[]; static void common_shutdown(void) { - syslog(LOG_INFO, "Stopping..."); + if (daemon_process && log_syslog) { + info("stopping..."); + } pidfile_close(); - for (int i = -1; __madexit[i]; i--) { (*__madexit[i])(); }