如何更改Linux进程的时区。

huangapple go评论89阅读模式
英文:

how do I change timezone of a linux process

问题

我有一个包含时间同步模块的程序。
该模块将时间与新时区和时间戳同步。
首先,它通过设置 /etc/timezone 和 /etc/localtime 来更改时区,然后使用时间戳设置系统时间。

我尝试了两种方法来设置系统时间:

int set_time(uint64_t ts) {
#if 0
    //第一种方法
    struct timeval tv;
    tv.tv_sec = ts;
    tv.tv_usec = 0;
    if (settimeofday(&tv, NULL) != 0) {
        return -1;
    }
#else
    //第二种方法
    char cmd[256];
    snprintf(cmd, sizeof(cmd), "date -s @%lld", ts);
    if (system(cmd) != 0) {
        return -1;
    }
#endif
    return 0;
}

两种方法都不按我预期的方式工作。
在调用此函数之后,系统时间会根据时间戳和新时区更改,但程序中打印的日期时间似乎仍然使用旧时区(我使用 API time 和 localtime_r 来获取当前日期时间)。
然而,在重新启动程序后,程序中打印的日期时间开始与系统时间相同。

我希望在调用时间同步 API 后,程序中的日期时间与系统时间相同。

英文:

I have a program which contains a time syncing module.
The module syncs time with a new timezone and a timestamp.
It changes timezone to the new one by setting up /etc/timezone and /etc/localtime at first, and then set system time using the timestamp.

I tried two methods to set the system time:

int set_time(uint64_t ts) {
#if 0
    //first method
    struct timeval tv;
    tv.tv_sec = ts;
    tv.tv_usec = 0;
    if (settimeofday(&tv, NULL) != 0) {
        return -1;
    }
#else
    //second method
    char cmd[256];
    snprintf(cmd, sizeof(cmd), "date -s @%lld", ts);
    if (system(cmd) != 0) {
        return -1;
    }
#endif
    return 0;
}

Both method doesn't work as I intended.
After call to this function, the system time is changed according to the timestamp and the new timezone, but the date time printed in the program seems still using the old timezone.(I use the api time and localtime_r to get the current date time.)
However, after I restart the program, the date time printed in the program start to become the same to the system time.

What I want is the date time in the program became the same as the system time after I call the time syncing apis.

答案1

得分: 2

如果你想在程序运行时让你的libc从/etc重新读取时区信息,最简单的方法是:

#include <time.h>
#include <stdlib.h>

...
unsetenv("TZ");
tzset();

解释(man tzset):

tzset()函数从TZ环境变量初始化tzname变量。...如果环境中没有TZ变量,则使用系统时区。系统时区通过将tzfile(5)格式的文件复制或链接到/etc/localtime来配置。

英文:

If you want your libc to re-read time zone information from /etc while your program is running, the simplest way is:

#include &lt;time.h&gt;
#include &lt;stdlib.h&gt;

...
unsetenv(&quot;TZ&quot;);
tzset();

Explanation (man tzset):

> The tzset() function initializes the tzname variable from the TZ
> environment variable. ... If the TZ variable does not appear in the
> environment, the system timezone is used. The system timezone is
> configured by copying, or linking, a file in the tzfile(5) format to
> /etc/localtime.

huangapple
  • 本文由 发表于 2023年2月14日 19:17:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447046.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定