【问题标题】:How do I check whether my system's clock is synchronized to a NTP server?如何检查我的系统时钟是否与 NTP 服务器同步?
【发布时间】:2020-12-17 13:52:43
【问题描述】:

我在 Linux 系统 (Ubuntu Server) 上有一个应用程序,它需要知道当前系统时钟是否已同步到 NTP 服务器。虽然我可以检查timedatectlSystem clock synchronized: yes 输出,但这似乎很脆弱,特别是因为timedatectl 的人类可读输出将来可能会发生变化。

不过,systemd 似乎充满了 DBus 接口,所以我怀疑可能有办法检查那里。不管怎样,我正在寻找bool is_ntp_synchronized()

有什么方法可以简单地检查系统时钟是否同步而无需启动另一个进程?

【问题讨论】:

  • 注意:您想知道NTP是否同步时间,或者计算机是否将时间同步到服务器? [对于第一个:您可以使用连接到 NTP 守护程序的硬件(例如 GPS 时钟)。第二个,过去我们有ntpdate,定期调用,但没有运行ntp守护进程]。

标签: c linux ntp


【解决方案1】:

Linux 提供adjtimex,也提供gets used by systemd。您可以检查各个字段以确定您是否仍处于同步状态。不等于 TIME_ERROR 的非负返回值可能是您的强项,尽管您可以使用 maxerror 或其他字段来检查时钟的质量。

#include <stdio.h>
#include <sys/timex.h>

int main()
{
    struct timex timex_info = {};
    timex_info.modes = 0;         /* explicitly don't adjust any time parameters */

    int ntp_result = ntp_adjtime(&timex_info);

    printf("Max       error: %9ld (us)\n", timex_info.maxerror);
    printf("Estimated error: %9ld (us)\n", timex_info.esterror);
    printf("Clock precision: %9ld (us)\n", timex_info.precision);
    printf("Jitter:          %9ld (%s)\n", timex_info.jitter,
           (timex_info.status & STA_NANO) ? "ns" : "us");
    printf("Synchronized:    %9s\n", 
           (ntp_result >= 0 && ntp_result != TIME_ERROR) ? "yes" : "no");
    return 0;
}

注意systemd explicitly ignores 报告的结果(错误除外),而是检查timex_info.maxerror 的值是否未超过16 秒。

这个接口也已经provided since the pre-git times了。因此,它可以保证是稳定的,否则它可能会破坏 Linux 的 don't-break-userspace-policy。

【讨论】:

    猜你喜欢
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多