c - `timer_settime()` 的奇怪行为

标签 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,我尝试删除优化,没有任何变化。

最佳答案

/* 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/

相关文章:

c - 从 Fortran 运行时 METIS 段错误

linux - 如何在 Linux 中复制多个文件的开头?

c - 尝试使用陷阱标志和陷阱信号处理程序单步执行程序,在 vsyscall 上崩溃

c++ - Qt/C++ 基于比较的信号调度的优雅方式

c - 在 Gracenote GNSDK 脚本中转义双引号

c - bss段有什么用?

php - 安装 Composer 时出错 - curl : (23) Failed writing body (0 ! = 16133)

django - 如何解决涉及 haystack 的循环导入?

将西类牙语字符串转换为大写

linux - 并排差异 (-y) : how to hide the reverse-video ^M (at end-of-line)?