关于用采用单独的线程对信号进行处理的问题
代码:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <apue.h>
int anaFlag = 0; //The flag of analysis
sigset_t mask;
pthread_mutex_t anaFlag_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t anaFlag_signal = PTHREAD_COND_INITIALIZER;
void *
sig_handler(void *arg)
{
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0)
err_exit(err, "sigwait failed");
switch (signo) {
case SIGUSR1:
pthread_mutex_lock(&anaFlag_lock);
anaFlag = 1;
pthread_mutex_unlock(&anaFlag_lock);
pthread_cond_signal(&anaFlag_signal);
break;
case SIGUSR2:
pthread_mutex_lock(&anaFlag_lock);
anaFlag = 0;
pthread_mutex_lock(&anaFlag_lock);
pthread_cond_signal(&anaFlag_signal);
break;
default:
err_sys("unexpected signal %d\n", signo);
}
}
}
int
main(void)
{
int ret;
pthread_t signalTid;
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigaddset(&mask, SIGUSR2);
if ((ret = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
err_exit(ret, "SIG_BLOCK error");
if ((ret = pthread_create(&signalTid, NULL, sig_handler, 0)) != 0)
err_exit(ret, "can't create thread");
pthread_mutex_lock(&anaFlag_lock);
printf("befor analysis, wait signal, anaFlag=%d\n", anaFlag);
while (anaFlag == 0)
pthread_cond_wait(&anaFlag_signal, &anaFlag_lock);
pthread_mutex_unlock(&anaFlag_lock);
/* analyse something... */
printf("analysis start, anaFlag=%d\n",anaFlag);
// analyse();
pthread_mutex_lock(&anaFlag_lock);
while (anaFlag == 1){
pthread_cond_wait(&anaFlag_signal, &anaFlag_lock);
}
pthread_mutex_unlock(&anaFlag_lock);
/* after analysis */
printf("after analysis, wait signal, anaFlag=%d\n",anaFlag);
// stopAnalyse();
/* deal with the result ... */
exit(0);
}
程序想实现的功能是:当程序接收到SIGUSR1信号时,启动analysis过程,当收到SIGUSR2时,停止analysis过程。线程signalTid负责 处理 SIGUSR1 和 SIGUSR2 信号。
可程序的实际运行结果是:程序能接收到SIGUSR1信号,并启动analysis过程,能收到SIGUSR2信号,但主线程却停在“pthread_cond_wait(&anaFlag_signal, &anaFlag_lock);”,并不能收到sig_handler发过来的信号“pthread_cond_signal(&anaFlag_signal);”。
哪位大虾知道这是为什么啊?能否解答下,谢谢!!
------解决方案--------------------
代码太乱没心思看,你的目的用pthread_sigmask就可以实现,不想处理信号的线程block所有的信号,处理信号的线程不block信号就可以。