So I have the following, working, code for getting clean exit performed when user interrupts the program (ie. ctrl-c in terminal), so that global destructors, etc. will be run. The problem is that it is very limited what you can do in the signal handler function (it did take me a little while to figure out how to this correctly (as simpel as it looks now) - the trick is starting a thread to moniter a flag - but now im left wondering if theres a better way to avoid burning cpu ? (in particular now as i plan to include this with some library code)
std::signal(SIGINT, [](int signal) { gSignalStatus() = signal; });
std::thread signal_handler_thread([] {
using namespace std::chrono_literals;
for (;;)
{
if (gSignalStatus() != 0)
{
std::exit(gSignalStatus());
}
std::this_thread::sleep_for(100ms);
}
});
signal_handler_thread.detach();
Sleeping is a very very crude solution - but is there any better way (for example wake up the thread from the signal handler, but we are not allowed to that...) ?