How to make an application detect if system time has changed in Linux

11,369

I think this article has an answer to your question: Notify userspace about time changes. But please note that the patch mentioned in the article is quite recent, so you have to check your linux kenel vesrion first.

If your kernel does not support userspace notification mechanism, then you can implement the following algorithm (in pseudocode):

time = gettimeofday()

loop:
    sleep 1 second
    new_time = gettimeofday()
    if (time_diff(new_time, time) > 2 seconds) then
       alert System time has changed by an external user/process!

    time = new_time
    goto loop

Hope this helps.

Share:
11,369

Related videos on Youtube

Vicky
Author by

Vicky

Updated on September 18, 2022

Comments

  • Vicky
    Vicky almost 2 years

    I need to write a small application which needs to detect if the system time is changed by an another application/user and perform some action as soon as it is detected (maybe log the data that time has changed, along with info about which application/user changed it).

    How can this be achieved?

    1. I have good programming experiences in shell script, c and beginner level in python.
    2. I don't need to know when it was changed, just need to know who/what changed it.
    3. The system uses NTP to sync the time, but it is also possible for anyone/any application to change the time(for eg: using the simple "date" command as well).
    • slhck
      slhck about 13 years
      You might want to add: What are your experiences in programming?
    • Almir Sarajčić
      Almir Sarajčić about 13 years
      If you're going to log the time that system time is changed, how will you say when it was changed? What's your reference?
    • Vicky
      Vicky about 13 years
      I have updated the description with the information requested
  • lapkritinis
    lapkritinis almost 4 years
    Note: time_diff should do abs() so there are no negative values.