From 920f925e4b58de30f0eeb205cf655dcb6e80ef95 Mon Sep 17 00:00:00 2001 From: Christian Kruse Date: Wed, 8 Jan 2014 11:53:15 +0100 Subject: [PATCH] added a new cli option --daemonize This option forks the process and generates a new session. This effectively detaches it from the shell. Don't forget to redirect stderr or use syslog for logging! --- errcode.h | 1 + repmgrd.c | 32 +++++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/errcode.h b/errcode.h index 208643c3..9bb84906 100644 --- a/errcode.h +++ b/errcode.h @@ -35,5 +35,6 @@ #define ERR_STR_OVERFLOW 10 #define ERR_FAILOVER_FAIL 11 #define ERR_BAD_SSH 12 +#define ERR_SYS_FAILURE 13 #endif /* _ERRCODE_H_ */ diff --git a/repmgrd.c b/repmgrd.c index 506dadad..6d616387 100644 --- a/repmgrd.c +++ b/repmgrd.c @@ -150,11 +150,13 @@ main(int argc, char **argv) {"config", required_argument, NULL, 'f'}, {"verbose", no_argument, NULL, 'v'}, {"monitoring-history", no_argument, NULL, 'm'}, + {"daemonize", no_argument, NULL, 'd'}, {NULL, 0, NULL, 0} }; int optindex; int c; + bool daemonize = false; char standby_version[MAXVERSIONSTR]; @@ -174,7 +176,7 @@ main(int argc, char **argv) } } - while ((c = getopt_long(argc, argv, "f:v:m", long_options, &optindex)) != -1) + while ((c = getopt_long(argc, argv, "f:v:md", long_options, &optindex)) != -1) { switch (c) { @@ -187,12 +189,39 @@ main(int argc, char **argv) case 'm': monitoring_history = true; break; + case 'd': + daemonize = true; + break; default: usage(); exit(ERR_BAD_CONFIG); } } + if (daemonize) + { + pid_t pid = fork(); + switch (pid) + { + case -1: + log_err("Error in fork(): %s\n", strerror(errno)); + exit(ERR_SYS_FAILURE); + break; + + case 0: // child process + pid = setsid(); + if (pid == (pid_t)-1) + { + log_err("Error in setsid(): %s\n", strerror(errno)); + exit(ERR_SYS_FAILURE); + } + break; + + default: // parent process + exit(0); + } + } + setup_event_handlers(); /* @@ -1116,6 +1145,7 @@ void help(const char *progname) printf(_(" --verbose output verbose activity information\n")); printf(_(" --monitoring-history track advance or lag of the replication in every standby in repl_monitor\n")); printf(_(" -f, --config_file=PATH configuration file\n")); + printf(_(" -d, --daemonize detach process from foreground\n")); printf(_("\n%s monitors a cluster of servers.\n"), progname); }