【问题标题】:Why changing timezone from shell does not affect gettimeofday() even after reboot?为什么即使在重新启动后从 shell 更改时区也不会影响 gettimeofday()?
【发布时间】:2015-02-06 21:44:59
【问题描述】:

我已经使用 dpkg-reconfigure tzdata 将 Ubuntu 时区从 UTC+2 更改为 UTC+0,但运行 C 代码 gettimeofday() 仍显示 tz_minuteswesttv_sec 在以前的时区中,即使在重新启动后也是如此。只有在 once 下运行 C 代码后,gettimeofday() 才开始显示 UTC+0 时间:

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

int main()
{
  struct timeval tv;
  struct timezone tz;

  setenv("TZ", "UTC", 1);
  tzset();

  gettimeofday(&tv, &tz);
  tv.tv_sec -= 7200;
  tz.tz_minuteswest = 0;
  settimeofday(&tv, &tz);

  gettimeofday(&tv, &tz);
  printf("time: %llu, offset: %d\n",
    (long long unsigned)tv.tv_sec, tz.tz_minuteswest);
}

是否有某种 gcc/libc 独立的时区配置?如何从 shell 更改整个系统的时区?

谢谢。

【问题讨论】:

  • 时区可以被 TZ 环境变量覆盖(这正是您在代码中所做的)。也许在程序启动之前 TZ 设置为 UTC-2?
  • 你的意思是我需要运行dpkg-reconfigure tzdata 并一起运行这个示例代码来调整整个系统的时区?
  • 没有。 tzdata 仅设置默认时区。每个用户和每个程序都可以使用环境变量 TZ 随意覆盖它。
  • 如何从 shell 检查环境变量? set | grep -i TZ 没有显示任何内容,即使在运行此示例代码并在没有 setenv() 调用的情况下再次运行它时,它已经显示正确的时间。

标签: c ubuntu timezone gettimeofday


【解决方案1】:

GNU 系统不支持使用struct timezone 表示时区信息;这是 4.3 BSD 的一个过时特性。相反,请使用Time Zone Functions 中描述的工具。

【讨论】:

  • 如何查看/更改 setenv() 调用设置的 TZ 变量的 shell 值?
  • 每个程序(包括shell)都有自己的环境。当您在程序中使用setenv() 更改它时,您不会在程序之外的任何地方看到它,但您可以在程序中使用getenv() 进行检查。
猜你喜欢
  • 1970-01-01
  • 2022-10-13
  • 2015-12-28
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
相关资源
最近更新 更多