mpdnotify: Daemonize at startup
Unless the `--no-fork` option is given, the program will fork into the background and return immediately to the caller.master
parent
5b3555fb92
commit
50cb3090dc
|
@ -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@ \
|
||||
|
|
|
@ -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();
|
||||
|
|
Loading…
Reference in New Issue