Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux strace 系統呼叫追蹤實戰指南:參數、輸出解讀與除錯案例

編輯:關於 Linux

strace 追蹤進程與核心的互動 (系統呼叫、訊號、進程狀態變更),是排查「為什麼程式掛了、卡住、找不到檔案」的核心工具。

基本用法

# 追蹤指令執行
strace ls

# 追蹤已運行進程 (PID 1234)
strace -p 1234

# 只追蹤特定系統呼叫
strace -e open,read,write ls

# 輸出時間戳與耗時
strace -tt -T ls

# 輸出到檔案
strace -o trace.log ls

輸出欄位解讀 (以 ls 為例)

strace 輸出開頭
write 系統呼叫
ls 實際輸出

  • execve("/bin/ls", ["ls"], [/* 環境變數 */]) = 0:程式進入點。
  • open("/lib64/ld-linux-x86-64.so.2", O_RDONLY|O_CLOEXEC) = 3:載入動態連結器。
  • write(1, "file1\nfile2\n", 12) = 12:向標準輸出 (fd=1) 寫入目錄列表。
  • exit_group(0):正常退出。

常見除錯場景

現象strace 切入點關鍵系統呼叫
程式啟動失敗strace -f -e trace=file ./appopen, access, stat (找不到庫/設定檔)
網路連線逾時strace -p PID -e trace=networkconnect, poll, recvfrom (卡在哪個階段)
權限被拒strace -e trace=file ./app回傳 EACCES (Permission denied) 的 open/mkdir
效能抖動strace -T -tt -o trace.log -p PID查看 <... 耗時 ...> 超過閾值的呼叫
進階技巧: -f 追蹤子進程 (fork/clone);-s 1024 增加字串顯示長度;-k 顯示堆疊回溯 (需核心支援);結合 grep 過濾關鍵字:strace -e open ls 2>&1 | grep -i denied。
Copyright © Windows教程網 All Rights Reserved