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