From e8f163976f4697cf68114fdc84092d8cad8c5bf4 Mon Sep 17 00:00:00 2001 From: Bent Bisballe Nyeng Date: Thu, 24 Aug 2023 20:21:42 +0200 Subject: Add option to fork to background and store pid in file. --- src/muniad.cc | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/muniad.cc b/src/muniad.cc index 7e260be..e225760 100644 --- a/src/muniad.cc +++ b/src/muniad.cc @@ -32,6 +32,8 @@ #include #include #include +#include +#include #include @@ -50,6 +52,8 @@ static struct lws_protocols protocols[] = static struct option options[] = { { "help", no_argument, nullptr, 'h' }, + { "background", no_argument, nullptr, 'b' }, + { "pidfile", required_argument, nullptr, 'P' }, { "port", required_argument, nullptr, 'p' }, { "file", required_argument, nullptr, 'f' }, { "ssl", no_argument, nullptr, 's' }, @@ -68,6 +72,8 @@ int main(int argc, char **argv) const char *key_path = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem"; + std::string pidfile; + bool background{false}; int port = 7681; int use_ssl = 0; struct lws_context *context; @@ -87,7 +93,7 @@ int main(int argc, char **argv) while(n >= 0) { - n = getopt_long(argc, argv, "ci:khsp:f:", options, nullptr); + n = getopt_long(argc, argv, "ci:khsp:f:P:b", options, nullptr); if(n < 0) { continue; @@ -106,6 +112,12 @@ int main(int argc, char **argv) case 'p': port = atoi(optarg); break; + case 'P': + pidfile = optarg; + break; + case 'b': + background = true; + break; case 'f': db_filename = strdup(optarg); break; @@ -115,12 +127,25 @@ int main(int argc, char **argv) interface = interface_name; break; case 'h': - fprintf(stderr, "Usage: muniad [--port=

] [--ssl] [--file=]\n"); + fprintf(stderr, "Usage: muniad [--port=

] [--ssl] [--file=] [--background] [--pidfile=]\n"); exit(1); } } //_parse("+all"); + if(background) + { + // Fork, chdir to / and redirect stdout and stderr to /dev/null + daemon(0, 0); + // Create a new session, make the current process process group leader. + setsid(); + } + + if(!pidfile.empty()) + { + std::ofstream fs(pidfile); + fs << getpid() << '\n'; + } node_manager.init(db_filename); -- cgit v1.2.3