I am writting a small server with forever loop and I want to have an ability to stop it correctly, for instance, on Ctrl + C (SIGINT).
class Server
{
...
public:
void loop()
{
while(_run_flag)
{
// do something
}
}
void stop()
{
_run_flag = 0;
}
...
private:
volatile sig_atomic_t _run_flag = 1;
};
namespace
{
std::function<void()> callback_wrapper;
void signal_handler(int)
{
callback_wrapper();
}
}
int main()
{
std::unique_ptr<WSGIServer> server = CreateServer("127.0.0.1", 4009);
callback_wrapper = [&](){ server->stop(); };
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = signal_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
server->loop();
return 0;
}
And I have the following questions:
- What is the type of
run_flag_variable
I should use? Is usingvolatile sig_atomic_t
ok? - Is it safe to call
stop
method insignal_handler
?