Skip to content

Commit

Permalink
Merge pull request #340 from Woazboat/signal-handler-non-daemon
Browse files Browse the repository at this point in the history
Install signal handlers for daemon and non-daemon mode
  • Loading branch information
mmd-osm authored Dec 11, 2023
2 parents bab0eec + 8946e90 commit 9f2a5ad
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,26 @@ void process_requests(int socket, const po::variables_map &options) {
req.dispose();
}

void install_signal_handlers() {
struct sigaction sa;

// install a SIGTERM handler
sa.sa_handler = terminate;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGTERM, &sa, NULL) < 0) {
throw std::runtime_error("sigaction failed");
}

// install a SIGHUP handler
sa.sa_handler = reload;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGHUP, &sa, NULL) < 0) {
throw std::runtime_error("sigaction failed");
}
}

/**
* make the process into a daemon by detaching from the console.
*/
Expand All @@ -265,21 +285,7 @@ void daemonise() {
throw std::runtime_error("setsid failed");
}

// install a SIGTERM handler
sa.sa_handler = terminate;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGTERM, &sa, NULL) < 0) {
throw std::runtime_error("sigaction failed");
}

// install a SIGHUP handler
sa.sa_handler = reload;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGHUP, &sa, NULL) < 0) {
throw std::runtime_error("sigaction failed");
}
install_signal_handlers();

// close standard descriptors
close(0);
Expand Down Expand Up @@ -382,6 +388,8 @@ void non_daemon_mode(const po::variables_map &options, int socket)
"[WARN] If the process terminates, it must be restarted externally.\n";
}

install_signal_handlers();

// record our pid if requested
if (options.count("pidfile")) {
std::ofstream pidfile(options["pidfile"].as<std::string>().c_str());
Expand Down

0 comments on commit 9f2a5ad

Please sign in to comment.