我想在收到SIGINT信号(正确地终止我的多线程C ++ 11的应用^C是),但由于某种原因,它不传播到子线程,但主线程响应很好。
对于instnce(如下面的代码样本中),如果我们有螺纹的内部的一些阻塞函数(如sleep()它会拿出所有^C如果您安装使用,也就是说,任何SIGNT钩子控制从您sigaction()功能。
有没有什么办法FIX-或变通这样的行为? 有没有一种方法,以主接收信号传播到子线程?
编辑 :取代POSIX sleep()与C ++ 11 std::this_thread::sleep_for()
#include
#include
#include
#include // 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因此,解决办法是更换无阻塞同行等机制,条件变量和查询所有阻塞调用。
实际的问题仍然没有答案为当前的软件(以及可能的硬件)在处理信号的方式是不是设计了然后在一个线程中,哪一个应该告诉别人在接收信号怎么办。