我正在尝试在接收到SIGINT信号(
例如(如下面的代码示例所示),如果在线程内部有一些阻塞函数(如
有没有办法修复或解决这种行为? 有没有办法将主收到的信号传播到子线程? 编辑:用C++11的
^C
)时正确终止我的多线程C++11应用程序,但出于某些原因它不会传播到子线程,尽管主线程对其做出了响应。例如(如下面的代码示例所示),如果在线程内部有一些阻塞函数(如
sleep()
),则如果您使用sigaction()
函数安装了任何SIGNT挂钩,它将带走所有 ^C
控制权。有没有办法修复或解决这种行为? 有没有办法将主收到的信号传播到子线程? 编辑:用C++11的
std :: this_thread :: sleep_for()
替换了POSIX的sleep()
。#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;
}
编辑2
解决方案是将所有阻塞调用替换为非阻塞调用,并使用条件变量和轮询等机制。
实际问题仍未得到解答,因为当前软件(可能还包括硬件)不是设计成处理多个线程接收信号的方式,并且必须有一个线程告诉其他线程在接收信号后该做什么。
sleep
函数与C++11线程混合使用? - Ben Voigtstd::this_thread::sleep_for()
。抱歉,让我更正我的示例。 - Alexander Tumin