Last active
August 29, 2015 14:25
-
-
Save vpArth/828502e40ca3ebf96ca2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <map> | |
#include <iostream> | |
#include <signal.h> | |
#include <unistd.h> | |
class Strategy | |
{ | |
public: | |
virtual void use(void) = 0; | |
}; | |
class StartStrategy: public Strategy {public: void use(void){ std::cout << "Starting..." << std::endl; }; }; | |
class StopStrategy: public Strategy {public: void use(void){ std::cout << "Stoping..." << std::endl; }; }; | |
class ReloadStrategy: public Strategy {public: void use(void){ std::cout << "Reloading..." << std::endl; }; }; | |
class UnknownStrategy: public Strategy {public: void use(void){ std::cout << "Unknown..." << std::endl; }; }; | |
class Runner | |
{ | |
protected: | |
Strategy* action; | |
public: | |
Runner(){} | |
Runner(Strategy* v){ this->set(v);} | |
Runner& run(void) {action->use(); return *this;} | |
Runner& set(Strategy* v) { action = v; return *this;} | |
}; | |
class SigManager | |
{ | |
private: | |
std::map<int, Strategy*> handlers; | |
struct sigaction sa; | |
Strategy *def; | |
public: | |
static volatile sig_atomic_t coming_sig; | |
SigManager() { | |
sa.sa_handler = SigManager::handle; | |
sa.sa_flags = SA_RESTART; | |
sigemptyset(&sa.sa_mask); | |
} | |
void addHandler(int signum, Strategy* s) { | |
handlers[signum] = s; | |
sigaddset(&sa.sa_mask, signum); | |
sigaction(signum, &sa, NULL); | |
} | |
void setDefault(Strategy* s) { | |
def = s; | |
} | |
static void handle(int sig) { | |
coming_sig = sig; | |
} | |
int run() { | |
Runner r; | |
while(1) { | |
sleep(10); | |
if (SigManager::coming_sig) { | |
if (handlers.count((int)SigManager::coming_sig)>0) { | |
r.set(handlers[(int)SigManager::coming_sig]); | |
} else { | |
if (!def) continue; | |
r.set(def); | |
} | |
r.run(); | |
if (SigManager::coming_sig == SIGUSR2) break; | |
SigManager::coming_sig = 0; | |
} | |
} | |
return 0; | |
} | |
}; | |
volatile sig_atomic_t SigManager::coming_sig = 0; | |
int main(int /*argc*/, char* /*argv*/[]) | |
{ | |
StartStrategy start; | |
StopStrategy stop; | |
ReloadStrategy reload; | |
UnknownStrategy unknown; | |
SigManager m; | |
m.addHandler(SIGUSR1, &start); | |
m.addHandler(SIGUSR2, &stop); | |
m.addHandler(SIGHUP, &reload); | |
m.setDefault(&unknown); | |
return m.run(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment