Implement daemonization

Now we're a real daemon, yay.
This commit is contained in:
Přemysl Eric Janouch 2014-07-16 23:26:50 +02:00
parent 1842fa90dd
commit a508f85bea
1 changed files with 36 additions and 5 deletions

View File

@ -1303,6 +1303,41 @@ on_signal_pipe_readable (const struct pollfd *fd, struct server_context *ctx)
} }
} }
static void
daemonize (void)
{
// TODO: create and lock a PID file?
print_status ("daemonizing...");
if (chdir ("/"))
exit_fatal ("%s: %s", "chdir", strerror (errno));
pid_t pid;
if ((pid = fork ()) < 0)
exit_fatal ("%s: %s", "fork", strerror (errno));
else if (pid)
exit (EXIT_SUCCESS);
setsid ();
signal (SIGHUP, SIG_IGN);
if ((pid = fork ()) < 0)
exit_fatal ("%s: %s", "fork", strerror (errno));
else if (pid)
exit (EXIT_SUCCESS);
openlog (PROGRAM_NAME, LOG_NDELAY | LOG_NOWAIT | LOG_PID, 0);
g_log_message_real = log_message_syslog;
// XXX: we may close our own descriptors this way, crippling ourselves
for (int i = 0; i < 3; i++)
xclose (i);
int tty = open ("/dev/null", O_RDWR);
if (tty != 0 || dup (0) != 1 || dup (0) != 2)
exit_fatal ("failed to reopen FD's: %s", strerror (errno));
}
static void static void
print_usage (const char *program_name) print_usage (const char *program_name)
{ {
@ -1396,12 +1431,8 @@ main (int argc, char *argv[])
exit (EXIT_FAILURE); exit (EXIT_FAILURE);
} }
// TODO: daemonize
if (!g_debug_mode) if (!g_debug_mode)
{ daemonize ();
openlog (PROGRAM_NAME, LOG_NDELAY | LOG_NOWAIT | LOG_PID, 0);
g_log_message_real = log_message_syslog;
}
ctx.polling = true; ctx.polling = true;
while (ctx.polling) while (ctx.polling)