簡體   English   中英

檢查time_t是否為零

[英]Check if time_t is zero

我用epoll和timerfd linux API編寫了一個計時器eventloop。 timerfd_gettime的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是否正確。 有人可以確認嗎?

親切的問候,大安

time_t類型別名是算術或實數類型。 算術和實數類型都可以與整數值零進行隱式比較。

此外,在POSIX系統(如Linux)上, time_t被定義為整數 (例如,請參見此<sys/types.h>參考 )。

盡管C標准沒有明確指定time_t的類型,但出於兼容性原因,幾乎所有實現都將time_t用作整數。 我不知道它不是整數的任何實現。

因此,您的問題的答案是比較是正確的。

應該注意的是,只有time_t類型的tv_sec成員。 tv_nsec成員是long

這不是內核實現中的錯誤。 有缺陷的是您的代碼。

it_value字段返回直到計時器下一次到期的時間。 如果此結構的兩個字段均為零,則計時器當前處於撤防狀態。

相反的是(假設調用timerfd_gettime()成功),如果結構的字段中的一個或兩個都不為零,則將計時器設防。

您的函數的最后一個return語句是

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM