1

我正在尝试将我的服务器时间与客户端时间同步,我得到了获取服务器时间的代码,如下所示。如果我在服务器中运行它,则在客户端登录时。我将向客户端发送时间,但是如何将“客户端”系统时间更改为我从服务器发送的时间。

我用谷歌搜索了 setenv 等,但我们如何真正改变 Linux C++ 中的时间?

使用下面的代码,我可以获得当前时间:

/* localtime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );

  return 0;
}
4

1 回答 1

3

A Linux (or Unix, or Posix) system measures the time from the unix epoch. No timezone is really involved at the lowest level (the time related syscalls, and the kernel). Timezone are a library thing, thru localtime(3) and strftime(3) and other functions.

Read also the time(7) man page.

You really want to synchronize time (on both local and remote machines) using the NTP protocol (use ntpd, chrony, ntpdate ....), or at least rdate (but NTP is preferable).

The system calls to query the time are gettimeofday(2), time(2), clock_gettime(2) with CLOCK_REALTIME

You might use settimeofday(2) and adjtimex(2) syscalls to set the time. This usually requires root privilege.

于 2012-08-20T11:35:46.657 回答