sig_atomic_t sigint = false;
sig_atomic_t sighup = false;
+bool daemon_process = true;
+int log_level = LOG_INFO;
+
static FILE *pidfile = NULL;
void common_sighandler(int sig)
{
switch (sig) {
+ case SIGTERM:
case SIGINT:
sigint = true;
return;
return;
default:
- syslog(LOG_ERR, "Killed (got signal %d)...", sig);
+ err("Killed (got signal %d)...", sig);
exit(-1);
}
}
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;
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;
- fprintf(pidfile, "%d\n", getpid());
+ if (fcntl(fileno(pidfile), F_SETLK, &lock) == -1) {
+ crit("program already started");
+ fclose(pidfile);
+ pidfile = NULL;
+ return -1;
+ }
+ fprintf(pidfile, "%d\n", getpid());
return fflush(pidfile);
}
return 0;
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);
- fclose(pidfile);
+ fcntl(fileno(pidfile), F_SETLK, &lock);
+ fclose(pidfile);
pidfile = NULL;
}
}
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);
+ if (!unsafe && drop_privileges(runas_user, runas_group) < 0) {
+ crit("unable to drop privileges");
return EXIT_FAILURE;
}
- if (!unsafe && drop_privileges(runas_user, runas_group) < 0) {
- syslog(LOG_CRIT, "unable to drop privileges");
+ if (daemonize && daemon_detach() < 0) {
+ crit("unable to fork");
return EXIT_FAILURE;
}
- if (daemonize && daemon_detach() < 0) {
- syslog(LOG_CRIT, "unable to fork");
+ if (pidfile_open(pidfilename) < 0) {
+ crit("unable to write pidfile %s", pidfilename);
return EXIT_FAILURE;
}
static void common_shutdown(void)
{
- syslog(LOG_INFO, "Stopping...");
- pidfile_close();
-
+ if (daemon_process) {
+ info("stopping...");
+ }
+ pidfile_close();
for (int i = -1; __madexit[i]; i--) {
(*__madexit[i])();
}