`timer_settime()`的奇怪行为

时间:2018-03-16 14:15:29

标签: c linux signals

我试图设置Linux计时器,以便每0.1秒(无限制)获取信号。我对timer_settime()电话有疑问。令人惊讶的是,这段代码似乎有效:

#define Msec 1e6
#define Cycle 100 * Msec

//...

#define SIGNO SIGRTMIN
struct sigaction sa = { .sa_handler = &each_cycle };
sigemptyset (&sa.sa_mask);

timer_t timer;
struct sigevent te = {
    .sigev_notify = SIGEV_SIGNAL,
    .sigev_signo = SIGNO,
    .sigev_value.sival_ptr = &timer
};

/* I don't know why this setting works. */
struct itimerspec it = {
    .it_interval.tv_nsec = Cycle,
    .it_value.tv_nsec = Cycle
};

if (sigaction (SIGNO, &sa, NULL) < 0 ||
    timer_create (CLOCK_REALTIME, &te, &timer) != 0 ||
    timer_settime (timer, 0, &it, 0) != 0
 ) {

    fprintf (stderr, "Unable to register timer.");
    return 1;
}

令人惊讶,因为根据我的不足,它应该导致一次后计时器到期。在我尝试.it_value.tv_sec = INT32_MAX之前 - 这似乎是最合理的,因为.it_value = {0,0}取消了计时器。 不幸的是,将tv_sec设置为任何值都会导致无信号。我在Raspberry Pi 3(GCC7)上运行Arch Linux,我试图删除优化,没有变化。

1 个答案:

答案 0 :(得分:0)

  

/* I don't know why this setting works. */ struct itimerspec it = { .it_interval.tv_nsec = Cycle, .it_value.tv_nsec = Cycle };

     

....    [A]根据我的理解,它应该会导致一次计时器到期。

设置it_interval武器定时器,在第一次到期后由it_value安排)进行间隔,重复到期。这就是你看到重复调用的原因。