I am trying to terminate correctly my multi-threaded C++11 application upon receiving SIGINT signal (^C
it is), but for some reason it does not propagate to child threads, though main thread responds to it well.
For instnce (as in code sample below), if we have a some blocking function inside of thread (like sleep()
), it will take out all ^C
control from you if you installed any SIGNT hooks using, say, sigaction()
function.
Is there any way to fix- or work-around such behavior? Is there a way to propagate main-received signals to child threads?
EDIT: replaced POSIX sleep()
with C++11 std::this_thread::sleep_for()
#include <iostream>
#include <thread>
#include <chrono>
#include <signal.h> // for sigaction() function
static int signaled = 0;
void threaded_foo() {
while (!signaled) {
// pressing ^C now will not lead to correct termination, because we are
// sleeping for a long time (100500 seconds) and do not respond to
// SIGINT for some tricky reason i am looking a bypassage for.
std::chrono::seconds duration(100500);
std::this_thread::sleep_for(duration);
}
std::cout << "Correct termination\n";
}
void sighandler(int sig, siginfo_t *siginfo, void *context) {
signaled = 1;
}
void install_sig_hooks() {
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_sigaction = sighandler;
action.sa_flags = SA_SIGINFO;
sigaction(SIGINT, &action, NULL);
}
int main(int argc, char **argv) {
install_sig_hooks();
std::thread t(threaded_foo);
t.join();
return 0;
}
EDIT2 So the solution was to replace all blocking calls with non-blocking counterparts and such mechanisms as condition variables and polling.
The actual question remains unanswered as current software (and, possibly, hardware) is not designed in way of handling signals more then in one thread, which one is supposed to tell others what to do upon receiving signals.