【问题标题】:running process does not follow system time运行进程不遵循系统时间
【发布时间】:2014-03-06 20:01:50
【问题描述】:

考虑以下程序,它除了每分钟打印一次时间之外什么都不做。 当我将 /etc/localtime 链接更改为不同的时区时,我希望它根据新时区打印时间,但它会继续使用启动时有效的时区。

如何让程序使用正确的时间,即使在运行时更改了时区?

顺便说一句,系统是CentOS 5.8

#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define MAX_STIME_LEN 32
int
main()
{
    while(1){
        struct timeval timev;
        gettimeofday(&timev,0);
        struct tm now_tm;
        time_t now = timev.tv_sec;
        char saved_time[MAX_STIME_LEN];
        strftime(saved_time, sizeof(saved_time), "%b %e %T", localtime_r (&now, &now_tm));
        printf("%s\n",saved_time);
        sleep(15);
    }
}

请注意,必须使用 localtime_r 和 strftime 而不是使用 ons-stop 调用。这只是一个例子。

【问题讨论】:

  • 在调用localtime_r()之前添加tzset(),并确保程序启动时没有设置TZ,修复问题。

标签: c linux time timezone


【解决方案1】:

好吧,我在这里找到了答案:stackoverflow.com/questions/19170721/...,只是我必须取消设置环境变量 TZ(即使它只是指向 /etc/localtime)

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2017-09-10
    相关资源
    最近更新 更多