Skip to content
Snippets Groups Projects
Commit 42fa09a6 authored by Adrien Béraud's avatar Adrien Béraud
Browse files

dhtnode: graceful signal handling in service and daemon modes

parent 673884a4
No related branches found
No related tags found
No related merge requests found
...@@ -386,8 +386,7 @@ main(int argc, char **argv) ...@@ -386,8 +386,7 @@ main(int argc, char **argv)
} }
if (params.daemonize or params.service) { if (params.daemonize or params.service) {
while (true) while (runner.wait());
std::this_thread::sleep_for(std::chrono::seconds(30));
} else { } else {
cmd_loop(dht, params); cmd_loop(dht, params);
} }
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
*/ */
// Common utility methods used by C++ OpenDHT tools. // Common utility methods used by C++ OpenDHT tools.
#pragma once
#include <opendht.h> #include <opendht.h>
#ifndef WIN32_NATIVE #ifndef WIN32_NATIVE
...@@ -37,6 +38,8 @@ ...@@ -37,6 +38,8 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <chrono> #include <chrono>
#include <mutex>
#include <condition_variable>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <fstream> #include <fstream>
...@@ -204,13 +207,33 @@ readLine(const char* prefix = PROMPT) ...@@ -204,13 +207,33 @@ readLine(const char* prefix = PROMPT)
return line_read ? std::string(line_read) : std::string("\0", 1); return line_read ? std::string(line_read) : std::string("\0", 1);
} }
struct ServiceRunner {
bool wait() {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [&]{return terminate;});
return !terminate;
}
void kill() {
std::lock_guard<std::mutex> lock(m);
terminate = true;
cv.notify_all();
}
private:
std::condition_variable cv;
std::mutex m;
bool terminate = false;
};
ServiceRunner runner;
void signal_handler(int sig) void signal_handler(int sig)
{ {
switch(sig) { switch(sig) {
case SIGHUP: case SIGHUP:
break; break;
case SIGINT:
case SIGTERM: case SIGTERM:
exit(EXIT_SUCCESS); runner.kill();
break; break;
} }
} }
...@@ -223,6 +246,7 @@ void setupSignals() ...@@ -223,6 +246,7 @@ void setupSignals()
signal(SIGTTOU,SIG_IGN); signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN); signal(SIGTTIN,SIG_IGN);
signal(SIGHUP,signal_handler); /* catch hangup signal */ signal(SIGHUP,signal_handler); /* catch hangup signal */
signal(SIGINT,signal_handler); /* catch interrupt signal */
signal(SIGTERM,signal_handler); /* catch kill signal */ signal(SIGTERM,signal_handler); /* catch kill signal */
#endif #endif
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment