开发者

How to detect change of system time in Linux?

开发者 https://www.devze.com 2022-12-20 03:47 出处:网络
Is there a way to get notified when there is update to the system time from a time-server 开发者_开发百科or due to DST change? I am after an API/system call or equivalent.

Is there a way to get notified when there is update to the system time from a time-server 开发者_开发百科or due to DST change? I am after an API/system call or equivalent.

It is part of my effort to optimise generating a value for something similar to SQL NOW() to an hour granularity, without using SQL.


You can use timerfd_create(2) to create a timer, then mark it with the TFD_TIMER_CANCEL_ON_SET option when setting it. Set it for an implausible time in the future and then block on it (with poll/select etc.) - if the system time changes then the timer will be cancelled, which you can detect.

(this is how systemd does it)

e.g.:

#include <sys/timerfd.h>
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

int main(void) {
        int fd = timerfd_create(CLOCK_REALTIME, 0);
        timerfd_settime(fd, TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET,
                        &(struct itimerspec){ .it_value = { .tv_sec = INT_MAX } },
                        NULL);
        printf("Waiting\n");
        char buffer[10];
        if (-1 == read(fd, &buffer, 10)) {
                if (errno == ECANCELED)
                        printf("Timer cancelled - system clock changed\n");
                else
                        perror("error");
        }
        close(fd);
        return 0;
}


I don't know if there is a way to be notified of a change in the system time, but

  • The system time is stored as UTC, so there is never a change due to DST change to be notified.

  • If my memory is correct, NTP deamon usually adjust the clock by changing its speed, again no change to be notified.

So the only times where you would be notified is after an uncommon manipulation.


clock_gettime on most recent Linux systems is incredibly fast, and usually pretty amazingly precise as well; you can find out the precision using clock_getres. But for hour level timestamps, gettimeofday might be more convenient since it can do the timezone adjustment for you.

Simply call the appropriate system call and do the division into hours each time you need a timestamp; all the other time adjustments from NTP or whatever will already have been done for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号