歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 手把手教你用 strace 診斷問題

手把手教你用 strace 診斷問題

日期:2017/2/28 13:57:03   编辑:Linux教程

早些年,如果你知道有個 strace 命令,就很牛了,而現在大家基本都知道 strace 了,如果你遇到性能問題求助別人,十有八九會建議你用 strace 掛上去看看,不過當你掛上去了,看著滿屏翻滾的字符,卻十有八九看不出個所以然。本文通過一個簡單的案例,向你展示一下在用 strace 診斷問題時的一些套路。

如下真實案例,如有雷同,實屬必然!讓我們看一台高負載服務器的 top 結果:

top

技巧:運行 top 時,按「1」打開 CPU 列表,按「shift+p」以 CPU 排序。

在本例中大家很容易發現 CPU 主要是被若干個 PHP 進程占用了,同時 PHP 進程占用的比較多的內存,不過系統內存尚有結余,SWAP 也不嚴重,這並不是問題主因。

不過在 CPU 列表中能看到 CPU 主要消耗在內核態「sy」,而不是用戶態「us」,和我們的經驗不符。Linux 操作系統有很多用來跟蹤程序行為的工具,內核態的函數調用跟蹤用「strace」,用戶態的函數調用跟蹤用「ltrace」,所以這裡我們應該用「strace」:

  1. shell>strace-p <PID>

不過如果直接用 strace 跟蹤某個進程的話,那麼等待你的往往是滿屏翻滾的字符,想從這裡看出問題的症結並不是一件容易的事情,好在 strace 可以按操作匯總時間:

  1. shell>strace-cp<PID>

通過「c」選項用來匯總各個操作的總耗時,運行後的結果大概如下圖所示:

strace -cp

很明顯,我們能看到 CPU 主要被 clone 操作消耗了,還可以單獨跟蹤一下 clone:

  1. shell>strace-T -e clone-p <PID>

通過「T」選項可以獲取操作實際消耗的時間,通過「e」選項可以跟蹤某個操作:

strace -T -e clone -p

很明顯,一個 clone 操作需要幾百毫秒,至於 clone 的含義,參考 man 文檔:

clone() creates a new process, in a manner similar to fork(2). It is actually a library function layered on top of the underlying clone() system call, hereinafter referred to as sys_clone. A description of sys_clone is given towards the end of this page.

Unlike fork(2), these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. (Note that on this manual page, “calling process” normally corresponds to “parent process”. But see the description of CLONE_PARENT below.)

簡單來說,就是創建一個新進程。那麼在 PHP 裡什麼時候會出現此類系統調用呢?查詢業務代碼看到了 exec 函數,通過如下命令驗證它確實會導致 clone 系統調用:

  1. shell>strace-eclone php -r 'exec("ls");'

最後再考大家一個題:如果我們用 strace 跟蹤一個進程,輸出結果很少,是不是說明進程很空閒?其實試試 ltrace,可能會發現別有洞天。記住有內核態和用戶態之分。

Linux strace命令詳解 http://www.linuxidc.com/Linux/2012-12/75671.htm

Linux strace 跟蹤進程信息 http://www.linuxidc.com/Linux/2012-10/72432.htm

Linux下重量級命令strace使用介紹 http://www.linuxidc.com/Linux/2012-10/71823.htm

Linux strace解決段錯誤 http://www.linuxidc.com/Linux/2011-08/41308.htm

Linux進程控制--strace:追蹤信號和系統調用 http://www.linuxidc.com/Linux/2011-05/35823.htm

Linux中程序執行的流程分析工具——strace http://www.linuxidc.com/Linux/2013-11/93023.htm

Copyright © Linux教程網 All Rights Reserved