C和C++标准支持信号的概念.但是,C11标准表示无法在多线程环境中调用函数signal(),或者行为未定义.但我认为信号机制本质上适用于多线程环境.
引用C11标准7.14.1.1.7
"在多线程程序中使用此函数会导致未定义的行为.实现的行为就像没有库函数调用信号函数一样."
对此有何解释?
以下代码不言而喻.
#include <thread>
#include <csignal>
using namespace std;
void SignalHandler(int)
{
// Which thread context here?
}
void f()
{
//
// Running in another thread context.
//
raise(SIGINT); // Is this call safe?
}
int main()
{
//
// Register the signal handler in main thread context.
//
signal(SIGINT, SignalHandler);
thread(f).join();
}
Run Code Online (Sandbox Code Playgroud) 我有一个侦听新连接的线程
new_fd = accept(Listen_fd, (struct sockaddr *) & their_addr, &sin_size);
Run Code Online (Sandbox Code Playgroud)
和另一个在关闭程序时关闭Listen_fd的线程.然而,在Listen_fd关闭后,它仍然会阻塞.当我使用GDB尝试和调试时,accept()不会阻塞.我认为这可能是SO_LINGER的问题,但默认情况下它不应该打开,并且在使用GDB时不应该更改.有什么想法,或关闭列表套接字的任何其他建议?