diff --git a/main.c b/main.c index b524e738..01cdae0a 100644 --- a/main.c +++ b/main.c @@ -68,6 +68,8 @@ static const char *verbosity_colors[] = { [LOG_DEBUG ] = "\x1B[1;30m", }; +static bool daemonize = false; + static enum log_importance log_importance = LOG_INFO; void swayidle_log_init(enum log_importance verbosity) { @@ -827,7 +829,7 @@ static int parse_idlehint(int argc, char **argv) { static int parse_args(int argc, char *argv[], char **config_path) { int c; - while ((c = getopt(argc, argv, "C:hdwS:")) != -1) { + while ((c = getopt(argc, argv, "C:hdfwS:")) != -1) { switch (c) { case 'C': free(*config_path); @@ -836,6 +838,9 @@ static int parse_args(int argc, char *argv[], char **config_path) { case 'd': swayidle_log_init(LOG_DEBUG); break; + case 'f': + daemonize = true; + break; case 'w': state.wait = true; break; @@ -848,6 +853,7 @@ static int parse_args(int argc, char *argv[], char **config_path) { printf(" -h\tthis help menu\n"); printf(" -C\tpath to config file\n"); printf(" -d\tdebug\n"); + printf(" -f\tdaemonize after initialization\n"); printf(" -w\twait for command to finish\n"); printf(" -S\tpick the seat to work with\n"); return 1; @@ -1016,6 +1022,25 @@ static int load_config(const char *config_path) { return 0; } +int do_daemonize(void) { + // don't close stdin, stdout, stderr + // just fork and setsid + pid_t child; + + child = fork(); + if (child < 0) { + return -1; + } + + if (child == 0) { + if (setsid() == -1) + return -1; + return 0; + } else { + swayidle_log(LOG_DEBUG, "Child forked, pid: %d", child); + _exit(0); + } +} int main(int argc, char *argv[]) { swayidle_init(); @@ -1118,6 +1143,13 @@ int main(int argc, char *argv[]) { display_event, NULL); wl_event_source_check(source); + if (daemonize) { + if (do_daemonize() != 0 ) { + swayidle_log_errno(LOG_ERROR, "Failed to daemonize, will exit!"); + sway_terminate(1); + } + } + while (wl_event_loop_dispatch(state.event_loop, -1) != 1) { // This space intentionally left blank } diff --git a/swayidle.1.scd b/swayidle.1.scd index 316dc3cb..5425c77a 100644 --- a/swayidle.1.scd +++ b/swayidle.1.scd @@ -21,6 +21,9 @@ swayidle - Idle manager for Wayland *-d* Enable debug output. +*-f* + Fork and daemonize after fully initialized. + *-w* Wait for command to finish executing before continuing, helpful for ensuring that a *before-sleep* command has finished before the system goes to sleep.