aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/kike.c41
1 files changed, 36 insertions, 5 deletions
diff --git a/src/kike.c b/src/kike.c
index 974f80f..709d027 100644
--- a/src/kike.c
+++ b/src/kike.c
@@ -1304,6 +1304,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
print_usage (const char *program_name)
{
fprintf (stderr,
@@ -1396,12 +1431,8 @@ main (int argc, char *argv[])
exit (EXIT_FAILURE);
}
- // TODO: daemonize
if (!g_debug_mode)
- {
- openlog (PROGRAM_NAME, LOG_NDELAY | LOG_NOWAIT | LOG_PID, 0);
- g_log_message_real = log_message_syslog;
- }
+ daemonize ();
ctx.polling = true;
while (ctx.polling)