定时器和信号问题 [英] Problem in Timers and signal

查看:23
本文介绍了定时器和信号问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 timer_create() API 实现了一个 POSIX 计时器,这将在计时器到期时生成 SIGUSR1,我已经为其放置了处理程序代码.现在的问题是,如果这个程序接收到另一个 SIGUSR1,那么将调用并捕获相同的信号处理程序.

I have implemented a POSIX timer using timer_create( ) API, and this will generate SIGUSR1 when the timer expires for which i have put a handler code. Now the problem is, if this program receives another SIGUSR1, then the same signal handler will be invoked and caught.

有什么办法可以防止这种情况发生,以便处理程序可以捕获仅由计时器生成的信号?

Is there any way to prevent this, so that the handler can catch signals only generated by the timer?

推荐答案

这对你有用吗?(修改了 timer_create 手册页中示例中的代码.)

Will this work for you? (Modified the code from example in timer_create man page.)

#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
");
    } else {
        printf("Caught signal %d from timer
", 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
", 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 将被显示.否则会显示杂散信号.

When signal from timer is caught Caught signal 10 from timer will be displayed. Otherwise Stray signal will be displayed.

这篇关于定时器和信号问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆