我在Linux系统(Ubuntu )上有一个应用程序,它需要知道当前系统时钟是否已同步到NTP服务器。虽然我可以检查timedatectl的System clock synchronized: yes输出,但这似乎非常脆弱,特别是因为timedatectl的人类可读的输出在未来可能会发生变化。
然而,systemd似乎充满了DBus接口,因此我怀疑可能有一种检查方法。不管怎样,我都在找bool is_ntp_synchronized()。
有没有任何方法可以简单地检查系统时钟是否同步而不启动另一个进程?
发布于 2020-12-17 13:52:43
Linux提供adjtimex,这也是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;
}请注意,显式忽略将报告的结果(除错误外)并检查timex_info.maxerror值是否不超过16秒。
这个接口也是从前吉特时代起。因此,它保证是稳定的,因为它可能会破坏Linux的不中断用户空间策略。
https://stackoverflow.com/questions/65342065
复制相似问题