[英]sigwait() does not work in multithreaded program
I'm trying to write a multithreaded program which one thread (variable thread in below) is responsible to any asynchronous signals that might be set to this process.我正在尝试编写一个多线程程序,其中一个线程(下面的可变线程)负责可能设置为此进程的任何异步信号。
I am facing thread that uses sigwait() but does not react to any signals have been sent to process.我正面临使用 sigwait() 但对已发送到处理的任何信号没有反应的线程。 (like SIGUSR1 in below). (如下面的 SIGUSR1)。
static void * signal_thread(void *arg = nullptr)
{
int sig = -1;
sigset_t sigset;
sigfillset(&sigset);
pthread_sigmask(SIG_BLOCK, &sigset, NULL);
while(1)
{
int s = sigwait(&sigset, &sig);
if(s == 0)
printf("SIG %d recieved!...\n", sig);
usleep(20);
}
}
int main()
{
sigset_t signalset;
pthread_t thread;
pthread_create(&thread, NULL, &signal_thread, nullptr);
sigfillset(&signalset);
pthread_sigmask(SIG_BLOCK, &signalset, NULL);
while(1)
{
raise(SIGUSR1);
usleep(20);
}
}
The problem is concerned to two issues:问题涉及两个问题:
First, call of raise in main sent signal only to main thread not whole process.首先, main 中的 raise 调用只向主线程发送信号,而不是整个进程。
Secondly, std::cout should be used instead of printf in signal_thread.其次,应该在signal_thread 中使用std::cout 而不是printf。
raise(sig)
is the equivalent of calling pthread_kill(pthread_self(), sig)
. raise(sig)
相当于调用pthread_kill(pthread_self(), sig)
。
Since the main
thread raise()
s the signal, the SIGUSR1 will be generated for that thread and not for any other.由于main
线程raise()
是信号,因此将为该线程而不是其他线程生成 SIGUSR1。 Thus, your signal_thread
will be unable to sigwait()
for the USR1, which will be held pending for the thread that generated it.因此,您的signal_thread
将无法为 USR1 执行sigwait()
,它将为生成它的线程挂起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.