繁体   English   中英

没有root特权如何更改Linux系统时间?

[英]How can I change Linux system time without root privileges?

我的情况如下:我有一个C ++应用程序,该应用程序访问无线电接收机以从中获取时间信号,然后根据来自无线电信号的时间来更新系统时间。 为了安全起见,该应用程序不得以root特权运行。 从论坛线程中阅读了此建议之后,我尝试了如下代码片段:

tm              current_time;
struct timeval *epoch         = new timeval;

// current_time is filled with time data from the radio tuner here.

epoch -> tv_sec  = mktime (&current_time);
epoch -> tv_usec = 0;

if (difftime (epoch -> tv_sec, mktime (&this -> last_system_time_update)) > (time_t) receiver::SYSTEM_TIME_UPDATE_INTERVAL) {
  retval += setgid       ((uid_t) 0);
  retval += setuid       ((uid_t) 0);
  retval += prctl        (PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L);
  retval += setgid       (group_id);
  retval += setuid       (user_id);
  retval += settimeofday (epoch, NULL);
}

与建议相反,当我没有以root用户身份运行时,此代码片段将无法工作。 我总是得到errno = 1。

怎么了 并且:有解决方法吗?

您仍在尝试获取root特权。 如果您具有CAP_SYS_TIME功能,则只需要settimeofday()。

if (difftime (epoch -> tv_sec, mktime (&this -> last_system_time_update)) > 
(time_t) receiver::SYSTEM_TIME_UPDATE_INTERVAL) {
  retval += settimeofday (epoch, NULL);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM