21

它可以跟踪所有使用的系统调用。

但是 sys_call 与普通调用有什么不同呢?

4

3 回答 3

42

As Matthew said, strace uses the ptrace(2) system call to work its magic. ptrace is used to implement debuggers and other tools which need to inspect what another program is doing. Essentially, strace will call ptrace and attach to a target process.

Whenever the target process makes a system call, it will stop, and strace will be notified. strace will then inspect the registers and stack of the target process (also using ptrace) to determine what system call was being made (each call has a unique number, passed in a register) and what the arguments were. strace then resumes the process. When it returns from the system call, it is stopped, and strace is notified again, so it can inspect the return value. strace prints some information for the user each time this happens.

In response to your second question, a system call is different from a normal function call in that a system call is implemented in the kernel, while a regular function is implemented in userspace. That's a whole separate can of worms though.

于 2011-07-13T00:24:19.423 回答
11

我写了一篇关于 strace 工作原理的博文和一篇关于系统调用如何工作的更长的博文。

strace通过使用ptrace系统调用来工作,这会导致内核在每次通过系统调用进入或退出内核时停止被跟踪的程序。跟踪程序(在这种情况下strace)然后可以通过使用来检查程序的状态ptrace

strace根据系统的工作方式获取每个系统调用的参数。在 x86-64 系统上,系统调用的参数在 CPU 寄存器中传递。在这种情况下,strace可以使用参数调用ptracePTRACE_GETREGS获取寄存器值的副本并打印它们。

于 2016-06-30T17:08:42.017 回答
1

系统调用是用户和内核空间之间的接口。有关列表,请参见man 2 syscallssyscalls.h

它们不应与标准 C 库函数混淆,例如printf. 这些通常最终会调用系统调用,但不一定。此外,用户空间程序可以使用syscall函数直接调用 syscall。

于 2011-03-31T01:23:55.643 回答