clock_gettime是如何在linux上实现的?

时间:2017-03-07 20:53:38

标签: linux time

当我strace时:

#include <stdio.h>
#include <time.h>

int main()
{
  struct timespec ts;

  fprintf(stderr, "start!\n");

  clock_gettime(CLOCK_REALTIME, &ts);
  fprintf(stderr, "realtime %lu %lu\n", ts.tv_sec, ts.tv_nsec);

  clock_gettime(CLOCK_MONOTONIC, &ts);
  fprintf(stderr, "monotonic %lu %lu\n", ts.tv_sec, ts.tv_nsec);

  return 0;
}

我明白了:

execve("/tmp/x", ["/tmp/x"], [/* 72 vars */]) = 0
brk(NULL)                               = 0x13d0000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fed9a0d1000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=126501, ...}) = 0
mmap(NULL, 126501, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fed9a0b2000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0P\t\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1864888, ...}) = 0
mmap(NULL, 3967488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fed99ae5000
mprotect(0x7fed99ca5000, 2093056, PROT_NONE) = 0
mmap(0x7fed99ea4000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1bf000) = 0x7fed99ea4000
mmap(0x7fed99eaa000, 14848, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fed99eaa000
close(3)                                = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fed9a0b1000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fed9a0b0000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fed9a0af000
arch_prctl(ARCH_SET_FS, 0x7fed9a0b0700) = 0
mprotect(0x7fed99ea4000, 16384, PROT_READ) = 0
mprotect(0x600000, 4096, PROT_READ)     = 0
mprotect(0x7fed9a0d3000, 4096, PROT_READ) = 0
munmap(0x7fed9a0b2000, 126501)          = 0
write(2, "start!\n", 7start!
)                 = 7
write(2, "realtime 1488919932 97097045\n", 29realtime 1488919932 97097045
) = 29
write(2, "monotonic 258985 170149836\n", 27monotonic 258985 170149836
) = 27
exit_group(0)                           = ?
+++ exited with 0 +++

似乎没有涉及生成CLOCK_REALTIMECLOCK_MONOTONIC值的系统调用。这是如何实现的?我试图在汇编程序中逐步完成它但我必须没有注意到关键部分,因为我无法弄清楚它是如何完成的。

1 个答案:

答案 0 :(得分:1)

这是一个虚拟系统调用。也就是说,调用它不需要切换到内核模式 - 它在用户模式下执行以提高性能。如果您曾想知道linux-vdso.so.1输出中ldd的含义,那么这就是实现这些虚拟系统调用的地方。您可以了解更多here