如何使用settimeofday(2)? [英] how to use settimeofday(2)?
问题描述
我在这里做错了什么?我希望settimeofday()
更改系统时间,而不返回EINVAL
.
What am I doing wrong here? I expect settimeofday()
to change the system time, not return EINVAL
.
$ uname -a
Linux io 4.3.5-300.fc23.x86_64 #1 SMP Mon Feb 1 03:18:41 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
$ cat settimeofday.c
#include <sys/time.h>
#include <stdio.h>
int main()
{
struct timeval tv = {0, 0};
if (settimeofday(&tv, 0) == -1)
perror("settimeofday");
}
$ gcc settimeofday.c
$ sudo ./a.out
settimeofday: Invalid argument
该错误来自运行Fedora 23的Thinkpad T450.相同的代码在OS X上运行正常.
The error is coming from a Thinkpad T450 running Fedora 23. The same code runs fine on OS X.
编辑
为澄清起见,该命令以root用户身份执行:
To clarify, the command is being executed as root:
# whoami
root
# sudo ./a.out
settimeofday: Invalid argument
按预期,如果我以常规用户身份运行程序,则会得到EPERM而不是EINVAL:
As expected, I get EPERM not EINVAL if I run the program as a regular user:
$ ./a.out
settimeofday: Operation not permitted
推荐答案
提交 e1d7ba 于2015年中期引入Linux内核,并限制了tv_sec字段的值.该限制受系统正常运行时间的影响-有关详细信息,请参见提交消息和相关的LKML讨论.
Commit e1d7ba was introduced to the Linux kernel in mid-2015 and restricts the value of the tv_sec field. The restriction is influenced by system uptime -- see the commit message and related LKML discussion for details.
这就是导致settimeofday
调用返回EINVAL
的原因,并解释了为什么代码在OS X和较旧的Linux机器上运行.
That's what was causing the settimeofday
call to return EINVAL
and explains why the code runs on OS X and older Linux machines.
这篇关于如何使用settimeofday(2)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!