strace
进程与系统
用法
strace [-f] -p <pid>把进程发出的每个系统调用逐条打印出来,用来看它卡在哪里;输出走的是 stderr,要用 `2>&1` 转过来,需要 ptrace 权限(通常是 sudo),而且只有 Linux 有(macOS 用 dtruss)。
常用选项
| 选项 | 含义 |
|---|---|
| -p <pid> | Attach to a process that is already running. |
| -f | Follow child processes and threads too. |
| -e trace=openat,connect | Only the syscalls you care about. |
| -s 200 | Show 200 characters of each string instead of the default 32. |
| -o <file> | Write to a file, since output goes to stderr. |
| -c | A summary count per syscall instead of every line. |
| -tt | Timestamps with microseconds, to see where the time went. |
示例
strace -f -e trace=openat ./app 2>&1 | grep configFind which config file it actually reads.
sudo strace -p 1234 -s 200See what a stuck process is waiting on.
sudo dtruss -p 1234The macOS counterpart; needs elevated privileges and often SIP changes.
看什么在跑、什么在吃机器。先弄清是什么,再决定杀不杀。
怎么看
- 方括号 [ ] 表示这部分可以不写。
- 省略号 … 表示可以写多个。
- 选项区分大小写——有些命令里 -r 和 -R 不是一回事。
常见问题
Q. strace 是做什么的?
把进程发出的每个系统调用逐条打印出来,用来看它卡在哪里;输出走的是 stderr,要用 `2>&1` 转过来,需要 ptrace 权限(通常是 sudo),而且只有 Linux 有(macOS 用 dtruss)。
Q. 怎么写?
strace [-f] -p <pid> —— 方括号表示可以省略的部分。
Q. 值得记的选项有几个?
这里列了 7 个,完整列表在 man strace。这条命令属于进程与系统。
相关命令
man 手册: man strace