萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

使用 GDB 除錯 PHP 死循環:從進程掛載到調用棧定位問題代碼

當 PHP CLI 腳本(如 Swoole Worker)陷入死循環導致 CPU 100%、進程狀態為 R 時,傳統 var_dump/xdebug 難以介入。本文實戰演示如何使用 GDB 掛載運行中進程,透過多次中斷與回溯(bt)定位具體 PHP 代碼行號,快速鎖定死循環源頭。

問題現場重現

測試腳本 dead_loop.php 包含一個無限 while(1) 迴圈,內部反覆操作陣列、字符串:

# dead_loop.php
$array = range(0, 9999);
include __DIR__ . '/include.php';

# include.php
while (1) {
    usleep(10);
    $keys = array_flip($array);
    $index = array_search(rand(1500, 9999), $array);
    $str = str_repeat('A', $index);
    $strb = test($index, $str);
}
function test($index, $str) { return str_replace('A', 'B', $str); }

GDB 實戰步驟

1. 找到目標進程 PID

$ ps aux | grep dead_loop
htf  3834  2.6  0.2  166676 22060 pts/12  R+  10:50  0:12  php dead_loop.php

進程狀態 R(Running)且 CPU 高,疑似死循環。

2. 掛載 GDB 並獲取首次回溯

$ gdb -p 3834
(gdb) bt

首次 bt 顯示在 zend_mm_check_ptr、_efree 等記憶體管理函數中,說明進程正在頻繁分配/釋放記憶體。

3. 讓進程繼續運行,再次中斷獲取第二次回溯

(gdb) c          # 繼續執行
^C               # 幾秒後 Ctrl+C 中斷
(gdb) bt

第二次 bt 關鍵幀:

#0  _zend_mm_alloc_int ... at zend_alloc.c:1895
#1  _emalloc ... at zend_alloc.c:2425
#2  _zend_hash_index_update_or_next_insert ... at zend_hash.c:412
#3  zif_array_flip ... at array.c:2719
#4  zend_do_fcall_common_helper_SPEC ... at zend_vm_execute.h:643
#5  ZEND_DO_FCALL_SPEC_CONST_HANDLER ... at zend_vm_execute.h:2233
#6  execute (op_array=0x21d58b0) at zend_vm_execute.h:410

4. 定位具體 PHP 函數與文件

第 6 幀 execute 是 PHP 虛擬機執行入口,檢查 op_array:

(gdb) f 6
(gdb) p *op_array
$2 = {filename = 0x7f726424ba38 "/home/htf/wwwroot/include.php", line_start = 12, line_end = 15, ...}

filename 指向 include.php,行號 12-15,正是 while(1) 迴圈體所在區間。

5. 進一步檢查當前執行的 opcode

(gdb) p **executor_globals.opline_ptr
$4 = {handler = 0x93ff9c, op1 = {...}, op2 = {...}, result = {...}, extended_value = 0, lineno = 13, ...}

lineno = 13 精確定位到迴圈內第 13 行($keys = array_flip($array);),確認死循環熱點。

關鍵操作提醒

  • 進程狀態變化:gdb -p 後進程變 T(Tracing),獨佔 ptrace,無法同時 strace。
  • 多次中斷取樣:單次 bt 可能落在 GC/記憶體管理代碼,需 c → Ctrl+C → bt 多次採樣,統計高頻出現的用戶代碼幀。
  • 生產環境慎用:GDB 會暫停進程,若為線上服務請在維護窗口或備份節點操作。

擴展:針對 Swoole/Workerman 等常駐進程

同樣適用。若 Worker 池中僅單進程異常,ps aux 找出該 PID 即可掛載分析。建議在開發階段建立「GDB 除錯 SOP」,關鍵時刻能分鐘級定位死循環、死鎖、記憶體洩漏等疑難雜症。

copyright © 萬盛學電腦網 all rights reserved