sigwait在Linux(Fedora 13)vs OS X [英] sigwait in Linux (Fedora 13) vs OS X
问题描述
所以我试图创建一个信号处理程序使用pthreads在OS X和Linux上工作。下面的代码适用于OS X,但不适用于Fedora 13。
So I'm trying to create a signal handler using pthreads which works on both OS X and Linux. The code below works on OS X but doesn't work on Fedora 13.
应用程序相当简单。它产生一个pthread,寄存器SIGHUP并等待一个信号。在生成信号处理程序后,我在主线程中阻塞SIGHUP,因此信号应该只发送到signal_handler线程。
The application is fairly simple. It spawns a pthread, registers SIGHUP and waits for a signal. After spawning the signal handler I block SIGHUP in the main thread so the signal should only be sent to the signal_handler thread.
在OS X上这很好,运行并发送SIGHUP到它打印的进程Got SIGHUP。在Linux上,它只会杀死进程(并打印Hangup)。如果我注释掉signal_handler pthread_create的应用程序不会死。
On OS X this works fine, if I compile, run and send SIGHUP to the process it prints "Got SIGHUP". On Linux it just kills the process (and prints Hangup). If I comment out the signal_handler pthread_create the application doesn't die.
我知道应用程序得到sigwait和块,而不是返回信号代码,它只是杀死应用程序。
I know the application gets to the sigwait and blocks but instead of return the signal code it just kills the application.
我使用以下命令运行测试:
I ran the test using the following commands:
g++ test.cc -lpthread -o test
./test &
PID="$!"
sleep 1
kill -1 "$PID"
test.cc
#include <pthread.h>
#include <signal.h>
#include <iostream>
using namespace std;
void *signal_handler(void *arg) {
int sig;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
while (true) {
cout << "Wait for signal" << endl;
sigwait(&set, &sig);
if (sig == SIGHUP) {
cout << "Got SIGHUP" << endl;
}
}
}
int main() {
pthread_t handler;
sigset_t set;
// Create signal handler
pthread_create(&handler, NULL, signal_handler, NULL);
// Ignore SIGHUP in main thread
sigfillset(&set);
sigaddset(&set, SIGHUP);
pthread_sigmask(SIG_BLOCK, &set, NULL);
for (int i = 1; i < 5; i++) {
cout << "Sleeping..." << endl;
sleep(1);
}
pthread_join(handler, NULL);
return 0;
}
推荐答案
sigwait()
的POSIX规范:
The POSIX spec for sigwait()
says:
集合定义的信号在调用
到<$ c时必须有
$ c> sigwait();否则,行为
未定义。
The signals defined by set shall have been blocked at the time of the call to
sigwait()
; otherwise, the behavior is undefined.
你不这样做。如果您添加:
You're not doing this. If you add:
pthread_sigmask(SIG_BLOCK, &set, NULL);
$ b $ p < sigaddset()
,那么它可以正常工作。
to your signal_handler()
function immediately after the sigaddset()
, then it works correctly.
这篇关于sigwait在Linux(Fedora 13)vs OS X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!