计时器和信号出现问题
我已经使用timer_create()API实现了POSIX计时器,当计时器到期时,我将为其放置处理程序代码,这将生成SIGUSR1。现在的问题是,如果此程序收到另一个SIGUSR1,则将调用并捕获相同的信号处理程序。
有什么方法可以防止这种情况,以便处理程序可以捕获仅由计时器生成的信号?
回答:
这对您有用吗?(修改了timer_create
手册页中示例中的代码。)
#include <stdlib.h>#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#define CLOCKID CLOCK_REALTIME
#define SIG SIGUSR1
timer_t timerid;
static void handler(int sig, siginfo_t *si, void *uc)
{
if(si->si_value.sival_ptr != &timerid){
printf("Stray signal\n");
} else {
printf("Caught signal %d from timer\n", sig);
}
}
int main(int argc, char *argv[])
{
struct sigevent sev;
struct itimerspec its;
long long freq_nanosecs;
sigset_t mask;
struct sigaction sa;
printf("Establishing handler for signal %d\n", SIG);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
sigemptyset(&sa.sa_mask);
sigaction(SIG, &sa, NULL);
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIG;
sev.sigev_value.sival_ptr = &timerid;
timer_create(CLOCKID, &sev, &timerid);
/* Start the timer */
its.it_value.tv_sec = 10;
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = its.it_value.tv_sec;
its.it_interval.tv_nsec = its.it_value.tv_nsec;
timer_settime(timerid, 0, &its, NULL);
sleep(100);
exit(EXIT_SUCCESS);
}
当捕捉到来自定时器的信号时,Caught signal 10 from timer
将显示。否则Stray signal
将显示。
以上是 计时器和信号出现问题 的全部内容, 来源链接: utcz.com/qa/397634.html