From 50cb3090dc9532406f9a08cdd78e1f07f4f91259 Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Sat, 30 Aug 2014 22:13:21 -0500 Subject: [PATCH] mpdnotify: Daemonize at startup Unless the `--no-fork` option is given, the program will fork into the background and return immediately to the caller. --- Makefile.am | 3 ++- src/mpdnotify.vala | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Makefile.am b/Makefile.am index 8f2a0f2..a57bf78 100644 --- a/Makefile.am +++ b/Makefile.am @@ -13,7 +13,8 @@ mpdnotify_VALAFLAGS = \ --pkg json-glib-1.0 \ --pkg libmpdclient \ --pkg libnotify \ - --pkg libsoup-2.4 + --pkg libsoup-2.4 \ + --pkg posix LIBS = @LIBS@ \ @glib_LIBS@ \ diff --git a/src/mpdnotify.vala b/src/mpdnotify.vala index 0e83859..8d9e1ad 100644 --- a/src/mpdnotify.vala +++ b/src/mpdnotify.vala @@ -4,12 +4,15 @@ namespace MpdNotify { private static string host; private static int port; + private static bool no_fork; private const OptionEntry[] options = { {"host", 'h', 0, OptionArg.STRING, ref host, "MPD server hostname/address", "HOST" }, {"port", 'p', 0, OptionArg.INT, ref port, "MPD server port", "PORT" }, + {"no-fork", 'f', 0, OptionArg.NONE, ref no_fork, + "Do not fork into the background", null }, { null } }; @@ -34,6 +37,30 @@ namespace MpdNotify { ctx.parse(ref args); } + void daemonize() { + Posix.pid_t pid; + pid = Posix.fork(); + if (pid < 0) { + stderr.printf("Unable to fork: %s", Posix.strerror(errno)); + Posix.exit(1); + } else if (pid > 0) { + Posix.exit(0); + } + Posix.pid_t sid = Posix.setsid(); + if (sid < 0) { + stderr.printf("Unable to create new session: %s", + Posix.strerror(errno)); + Posix.exit(1); + } + pid = Posix.fork(); + if (pid < 0) { + stderr.printf("Unable to fork: %s", Posix.strerror(errno)); + Posix.exit(1); + } else if (pid > 0) { + Posix.exit(0); + } + } + int main(string[] args) { try { parse_args(args); @@ -42,6 +69,10 @@ namespace MpdNotify { return 2; } + if (!no_fork) { + daemonize(); + } + var loop = new MainLoop(); Unix.signal_add(2, () => { loop.quit();