我正在尝试设置 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,我尝试删除优化,没有任何变化。
最佳答案
/* I don't know why this setting works. */ struct itimerspec it = { .it_interval.tv_nsec = Cycle, .it_value.tv_nsec = Cycle };
.... [A]ccording to my understanding it should cause expiring of timer after one time.
设置 it_interval
在第一次到期后(由 it_value
安排)为间隔、重复到期设置定时器。这就是您看到重复调用的原因。
关于c - `timer_settime()` 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49322865/