5

一、开启

查看是否开启 core dump 输出

ulimit -a

打开 core dump 文件记录

ulimit -c unlimited

yum install gdb php-dbg

关闭 core dump 文件记录

ulimit -c 0

设置内核core dump出来的存放路径(注意目录要有权限给php写):
echo "/tmp/core.%e.%p.%t" > /proc/sys/kernel/core_pattern

二、调试

1、准备 .gdbinit 文件

获取地址:https://github.com/php/php-src/blob/master/.gdbinit
保存在服务器上,例如 /root/.gdbinit 备用。

2、用 gdb 打开 core 文件

gdb php-fpm -c core-php-fpm.920

可以看到类似下边的字样:

Core was generated by `php-fpm: pool www            '.
Program terminated with signal 11, Segmentation fault.

3、查看 core 发生时刻的堆栈

(gdb) bt
#0  zend_mm_alloc_small (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:1295
#1  zend_mm_alloc_heap (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:1366
#2  _emalloc (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:2450
#3  0x00007f7a6fad0511 in apm_sprintf (fmt=0x7f7a6faeff50 "\n %04d-%02d-%02d %02d:%02d:%02d Version %s\n Process %d received signal %2d: %s , bss[%p]\n")
    at /PHP/64/source/php7.0.0_nzts/ext/apm/apm_common.c:371
#4  0x00007f7a6facbefd in print_backtrace (sig=11) at /PHP/64/source/php7.0.0_nzts/ext/apm/apm.c:1937
#5  0x00007f7a6facbfd7 in agent_fatal_signal_handler (sig=11) at /PHP/64/source/php7.0.0_nzts/ext/apm/apm.c:1955
#6  <signal handler called>
#7  zend_mm_alloc_small (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:1295
#8  zend_mm_alloc_heap (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:1366

4、引入 PHP 源代码中提供的 .gdbinit (gdb 命令编写脚本)

(gdb) source /root/.gdbinit

5、查看 backtrace 和变量值

(gdb) zbacktrace
[0x7f7a75e138c0] C("DEBUG") /usr/share/nginx/html/smartphp/common.php:28
[0x7f7a75e137d0] Model->_connectDb() /usr/share/nginx/html/smartphp/core/Model.class.php:44
[0x7f7a75e13680] Model->bindData("SELECT\40tips\40FROM\40keyword_phone\40WHERE\40word=:word", array(1)[0x7f7a75e136f0], "getdata") /usr/share/nginx/html/smartphp/core/Model.class.php:143
[0x7f7a75e13580] Model->getData("SELECT\40tips\40FROM\40keyword_phone\40WHERE\40word=:word", array(1)[0x7f7a75e135f0]) /usr/share/nginx/html/smartphp/core/Model.class.php:215
[0x7f7a75e134c0] Model->getField("SELECT\40tips\40FROM\40keyword_phone\40WHERE\40word=:word", array(1)[0x7f7a75e13530]) /usr/share/nginx/html/appdata/smartphp/core/Model.class.php:264
(gdb) print ((zval *)0x7f7a75e13530)
$1 = (zval *) 0x7f7a75e13530

(gdb) printzv $1
[0x7f7a75e13530] (refcount=3) array:     Packed(1)[0x7f7a75e94888]: {
      [0] 0 => [0x7f7a75e6ad88] (refcount=4) string: PP红包。
}

https://bugs.php.net/bugs-generating-backtrace.php
http://www.laruence.com/2011/06/23/2057.html
https://kn007.net/topics/php-fpm-how-to-core-dump/
http://www.laruence.com/2011/12/06/2381.html


风逐蓝天
2.5k 声望89 粉丝