我有一个程序,我调用信号sigkill(getpid(), SIGUSR1)
。 我希望信号来的时候,而不是信号处理程序的线程函数应该被调用,或两者。 为此,我已经使用SIGEV_THREAD
填充了SIGEV_THREAD
。
但不幸的是,线程函数不被调用。 为什么这样?
这是下面的代码:
#include <stdlib.h> #include <time.h> #include <stdio.h> #include <signal.h> #include <errno.h> #include <string.h> static void ThreadhandlerTimer1(int); void sig_handlerTimer1(int); static void threadFunction(union sigval sv) // Should be invoked on receipt of signal "SIGEV_THREAD" { printf("Thread function invoked"); } int main() { int i; static struct sigaction sa; static struct sigevent sevp; memset (&sevp, 0, sizeof (struct sigevent)); sevp.sigev_value.sival_ptr = NULL; sevp.sigev_notify = SIGEV_THREAD; sevp.sigev_notify_attributes = NULL; sevp.sigev_signo = SIGUSR1; sevp.sigev_notify_function=threadFunction; /* Setting the signal handlers */ sa.sa_handler = sig_handlerTimer1; sa.sa_flags = 0; sigaction(SIGUSR1, &sa, NULL); for(i=0; i<10; i++) { if((i==3) || (i==6)){ kill(getpid(), SIGUSR1); } printf("%d\n",i); sleep(1); } } void sig_handlerTimer1(int signum) { printf("Caught signal: %d\n",signum); }
根据本文档 , sigevent
结构仅支持“高分辨率定时器到期,异步I / O完成,进程间消息到达和sigqueue()”等一些信号生成功能。
我不知道你的代码真正的计划是什么(也许你可以告诉我们),但是实际上,你直接提高了信号,这可能不是使用SIGEV支持的情况之一。 如果这段代码和你在生产中想要的非常接近,你可以简单地调用sigqueue()
而不是kill()
,它可能正常工作。
从你的代码看来,你刚刚为sigevent赋值,而不是使用代码中的任何地方。
static struct sigevent sevp;
memset (&sevp, 0, sizeof (struct sigevent)); sevp.sigev_value.sival_ptr = NULL; sevp.sigev_notify = SIGEV_THREAD; sevp.sigev_notify_attributes = NULL; sevp.sigev_signo = SIGUSR1; sevp.sigev_notify_function=threadFunction;
调用threadFunction,从你的信号处理程序调用它。
> void sig_handlerTimer1(int signum) > { > printf("Caught signal: %d\n",signum); > threadFunction(signum); > }
如果你想使用sevp ,使用诸如timer_create()和timer_settime()之类的东西。 检查这个链接: http : //ptgmedia.pearsoncmg.com/images/0201633922/sourcecode/sigev_thread.c