为什么使用 strace 只捕获一次系统调用(getpid)?

Inf*_*ite 5 libc system-calls linux-kernel strace

我在一个程序中多次调用getpid()(为了测试系统调用的效率),但是当我strace用来获取trace时,只捕获了一个getpid()调用。

代码很简单:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

void print_usage(){
    printf("Usage: program count\n");
    exit(-1);
}

int main(int argc, char** argv){
    if(argc != 2)
        print_usage();
    int cnt = atoi(argv[1]);
    int i = 0;
    while(i++<cnt)
        getpid();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我使用gdb并得到了这个:

(gdb) disasse
Dump of assembler code for function getpid:
0xb76faac0 <getpid+0>:  mov    %gs:0x4c,%edx
0xb76faac7 <getpid+7>:  cmp    $0x0,%edx
0xb76faaca <getpid+10>: mov    %edx,%eax
0xb76faacc <getpid+12>: jle    0xb76faad0 <getpid+16>
0xb76faace <getpid+14>: repz ret 
0xb76faad0 <getpid+16>: jne    0xb76faadc <getpid+28>
0xb76faad2 <getpid+18>: mov    %gs:0x48,%eax
0xb76faad8 <getpid+24>: test   %eax,%eax
0xb76faada <getpid+26>: jne    0xb76faace <getpid+14>
0xb76faadc <getpid+28>: mov    $0x14,%eax
0xb76faae1 <getpid+33>: call   *%gs:0x10
0xb76faae8 <getpid+40>: test   %edx,%edx
0xb76faaea <getpid+42>: mov    %eax,%ecx
0xb76faaec <getpid+44>: jne    0xb76faace <getpid+14>
0xb76faaee <getpid+46>: mov    %ecx,%gs:0x48
0xb76faaf5 <getpid+53>: ret  
Run Code Online (Sandbox Code Playgroud)

我不太明白汇编代码。如果有人可以对此进行详细解释,也会有所帮助。根据我的观察,“call *%gs:0x10”(跳转到vdso)没有被执行,除了第一次getpid()调用,这可能是后续getpid()调用没有被捕获的原因。但我不知道为什么。

linux内核:2.6.24-29 gcc (GCC) 4.2.4 libc 2.7,

谢谢!

Mat*_*Mat 5

Glibc 缓存结果,因为它不能在调用之间改变。例如,请参阅此处的源代码。

所以真正的系统调用只会执行一次。其他调用只是从缓存中读取。(代码不是很简单,因为它负责用线程做正确的事情。)