1

I'm writing a software that is very sensitive to local time. I'm using boost::posix_time to get the local time of the computer. However, I noticed that if we change the time and the timezone during the execution, the local time gets totally wrong. Here is a small test program I wrote:

#include <boost/date_time/posix_time/posix_time.hpp>
#include <stdio.h>

int main(int argc, char* argv[])
{
  while(1)
  {
    std::cout << "It's : " << boost::posix_time::to_simple_string(
      boost::posix_time::second_clock::local_time()) << std::endl;
    sleep(1);
  }

  return 0;
}

Then I start the application, the time is correct:

./testDate 
It's : 2013-Apr-22 10:35:22

Then I change the time and the timezone during it's execution, and the time got totally wrong!

 rm /etc/localtime  ; ln -s /usr/share/zoneinfo/Europe/Belfast  /etc/localtime ; date -s 10:35:00

It's : 2013-Apr-22 10:35:16
It's : 2013-Apr-22 10:35:17  <-- Time changed here
It's : 2013-Apr-22 04:35:00
It's : 2013-Apr-22 04:35:01

But if I manually restart the application, the time is correct again! I was wondering if there is a way to tell boost to refresh the date time from the system clock? I guess it reads it once at startup and stores the time in memory. And how could I detect that the timezone or the time was changed and I have to tell boost to update the time? Check if the time is significantly different from the last time I got the time by regularly asking the time?

morandg
  • 1,066
  • 3
  • 14
  • 30
  • I suspect the problem is that the application (inside boost) opens the `/etc/localtime` file, and either keeps it open, or caches the value. I'm not entirely sure how you'd fix that - you could of course write your own code to detect that the `/etc/localtime` has changed and, perhapse, restart your own application? – Mats Petersson Apr 23 '13 at 09:03
  • 1
    You could use [`inotify`](http://en.wikipedia.org/wiki/Inotify) to get a report that the file has changed. – Matt Clarkson Apr 23 '13 at 09:05
  • OK then, I think I'll go with the "inotify" solution and restart the application but I would prefer asking boost to refresh this at runtime instead but it should work this way! – morandg Apr 24 '13 at 11:18
  • I think the behavior is actually related to how localtime_r() works on a POSIX system. Specifically it doesn't call tzset(). https://stackoverflow.com/questions/19170721/real-time-awareness-of-timezone-change-in-localtime-vs-localtime-r – Dusty Campbell Feb 13 '18 at 22:08

1 Answers1

0

I suspect this functionality was intentionally left out of boost as it would require an unnecessary performance hit for such an application-specific addition (or worse, possibly cluttering the api with functionality that is rarely needed). I agree with others that detection of the time change should be done in the user application.

Chris
  • 613
  • 6
  • 7