【发布时间】:2017-04-19 10:52:17
【问题描述】:
我希望gettimeofday() 会调用系统调用来完成实际获取时间的工作。但是,运行以下程序
#include <stdlib.h>
#include <sys/time.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
struct timeval tv;
printf("Before gettimeofday() %ld!\n", tv.tv_sec);
int rc = gettimeofday(&tv, NULL);
printf("After gettimeofday() %ld\n", tv.tv_sec);
if (rc == -1) {
printf("Error: gettimeofday() failed\n");
exit(1);
}
printf("Exiting ! %ld\n", tv.tv_sec);
return 0;
}
dtruss -d 下返回一长串系统调用,最后一个是:
RELATIVE SYSCALL(args) = return
... lots of syscalls with earlier timestamps ...
3866 fstat64(0x1, 0x7FFF56ABC8D8, 0x11) = 0 0
3868 ioctl(0x1, 0x4004667A, 0x7FFF56ABC91C) = 0 0
3882 write_nocancel(0x1, "Before gettimeofday() 0!\n\0", 0x19) = 25 0
3886 write_nocancel(0x1, "After gettimeofday() 1480913810\n\0", 0x20) = 32 0
3887 write_nocancel(0x1, "Exiting ! 1480913810\n\0", 0x15) = 21 0
看起来gettimeofday() 没有使用系统调用,但这似乎是错误的——内核肯定负责系统时钟吗? dtruss 有什么遗漏吗?我是不是读错了输出?
【问题讨论】:
-
在 Solaris 上,
gettimeofday()只是读取内存位置。 macOS Sierra(或之前的 Mac OS X 版本)很可能发生了类似的事情。您可能有兴趣也可能没有兴趣注意到 macOS Sierra(但不是早期版本)终于支持clock_gettime()。 -
可以在source code-#116中看到
gettimeofday()系统调用 -
在 Linux 上,
gettimeofday()等系统调用可以实现为“普通函数调用和少量内存访问”:vDSO
标签: c macos time operating-system system-calls