检查 time_t 是否为零

标签 c linux timer time-t

我用 epoll 和 timerfd linux API 编写了一个定时器事件循环。 timerfd_gettime 的网页说明如下:

The it_value field returns the amount of time until the timer will
next expire.  If both fields of this structure are zero, then the
timer is currently disarmed.

因此,为了检查计时器当前是处于启用还是解除状态,我编写了以下代码:

bool timer_is_running(struct timer *timer)
{
    struct itimerspec timerspec;

    if(timerfd_gettime(timer->_timer_fd, &timerspec) == -1) {
        printf("[TIMER] Could not  get timer '%s' running status\n", timer->name);
        return false;
    }

    printf("[TIMER] Checking running state of timer '%s' it_value.tv_sec = %"PRIu64", it_value.tv_nsec = %"PRIu64"\n", timer->name, (uint64_t) timerspec.it_value.tv_sec, (uint64_t) timerspec.it_value.tv_nsec == 0);
    return timerspec.it_value.tv_sec != 0  && timerspec.it_value.tv_nsec != 0;
}

这不起作用,所有计时器都被报告为已解除武装。当我查看输出时,我在当前解除武装的计时器上看到以下内容:

[TIMER] Checking running state of timer 'test' it_value.tv_sec = 0, it_value.tv_nsec = 4302591840

经过进一步调查,似乎只有 tv_sec 字段在解除计时器上设置为 0。

这是在 MIPS 架构 (OpenWRT) 的内核 3.18.23 上运行的程序。

在我将此标记为内核实现中的错误之前,我想知道通过执行 time_t == 0 检查 time_t 是否为 0 是否正确。谁能证实这一点?

亲切的问候, 大安

最佳答案

这不是内核实现中的错误。是您的代码有缺陷。

The it_value field returns the amount of time until the timer will next expire. If both fields of this structure are zero, then the timer is currently disarmed.

与此相反的是(假设调用 timerfd_gettime() 成功)如果结构的一个或两个字段不为零,则计时器会启动。

你的函数的最后一个返回语句是

return timerspec.it_value.tv_sec != 0  && timerspec.it_value.tv_nsec != 0;

仅当两个字段都非零时才返回 true。相反,您需要使用

return timerspec.it_value.tv_sec != 0  || timerspec.it_value.tv_nsec != 0;

关于检查 time_t 是否为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39191461/

相关文章:

c - 如何使 C 编译器将所有嵌套循环转换为单个循环

c - GtkEntry 中的限制值

linux - poll(2) 是否等待 fd 上的操作完成?

c - fread 从 Linux 磁盘读取扇区时返回 0

java - 我的计时器有什么问题吗?

c - Visual Studio C/C++ 数组大小未处理的异常堆栈溢出

c - 如何在 system() 函数中使用多个引号?

linux - 服务器上 setgid 位的用途是什么?

javascript - Jest setTimeout 不暂停测试

java - 如何使用 Java Timer 和 TimerTask 安排具有开始时间和结束时间的任务