系统调用的 strace 顺序与预期顺序不匹配

问题描述 投票:0回答:1

我希望

strace
与测试代码片段一起运行,以在
write
调用之前输出
open
调用,如 dissambly 所建议的那样。
puts
是否以某种方式异步执行写入,还是
strace
重新排序输出?

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

int main() {
   close(1);
   printf("Interesting ordering\n");
   int fd = open("temp.txt", O_RDONLY);
   int fd1 = open("temp.txt", O_RDONLY);
}

Strace 片段:

munmap(0x7fe46ef45000, 115047)          = 0
close(1)                                = 0
newfstatat(1, "", 0x7fffeea1b980, AT_EMPTY_PATH) = -1 EBADF (Bad file descriptor)
getrandom("\x96\xa6\x6b\xd0\x3c\xde\x09\x28", 8, GRND_NONBLOCK) = 8
brk(NULL)                               = 0xb18000
brk(0xb39000)                           = 0xb39000
openat(AT_FDCWD, "temp.txt", O_RDONLY)  = 1
openat(AT_FDCWD, "temp.txt", O_RDONLY)  = 3
write(1, "Interesting ordering\n", 21)  = -1 EBADF (Bad file descriptor)
exit_group(0)                           = ?

主体拆解:

0000000000401146 <main>:
  401146:   55                      push   %rbp
  401147:   48 89 e5                mov    %rsp,%rbp
  40114a:   48 83 ec 10             sub    $0x10,%rsp
  40114e:   bf 01 00 00 00          mov    $0x1,%edi
  401153:   e8 e8 fe ff ff          call   401040 <close@plt>
  401158:   bf 10 20 40 00          mov    $0x402010,%edi
  40115d:   e8 ce fe ff ff          call   401030 <puts@plt>
  401162:   be 00 00 00 00          mov    $0x0,%esi
  401167:   bf 25 20 40 00          mov    $0x402025,%edi
  40116c:   b8 00 00 00 00          mov    $0x0,%eax
  401171:   e8 da fe ff ff          call   401050 <open@plt>
  401176:   89 45 fc                mov    %eax,-0x4(%rbp)
  401179:   be 00 00 00 00          mov    $0x0,%esi
  40117e:   bf 25 20 40 00          mov    $0x402025,%edi
  401183:   b8 00 00 00 00          mov    $0x0,%eax
  401188:   e8 c3 fe ff ff          call   401050 <open@plt>
  40118d:   89 45 f8                mov    %eax,-0x8(%rbp)
  401190:   b8 00 00 00 00          mov    $0x0,%eax
  401195:   c9                      leave
  401196:   c3                      ret
system-calls strace
1个回答
0
投票

strace
显示的顺序是正确的:它是系统调用的顺序,而不是库调用的顺序。

printf
的调用通常会被缓冲,并且在您发出
fflush
之前不会真正写入。

代码的主要问题是,您将

stdio
库的调用与低级调用(例如
write()
)混合在一起;当您这样做时,结果是不确定的,可能会让您感到惊讶。

© www.soinside.com 2019 - 2024. All rights reserved.