Home  >  Article  >  php教程  >  当PHP内存泄漏时,如何检测?

当PHP内存泄漏时,如何检测?

PHPz
PHPzOriginal
2016-06-06 20:07:492172browse

一 PHP内置内存泄漏探测

PHP本身有自己的内存管理,在编译时,增加编译选项--enable-debug 以及相应扩展编译时加上 ./configure --enable-debug,这样编译后,使用命令行执行php test.php 如果有内存泄漏则会往 标准错误输出 打印错误信息。

注意:这个方法只能检测到使用了Zend内存管理的情况,对于直接使用malloc/free来申请内存的应用或扩展是无法检测到的。

二 valgrind

wget http://valgrind.org/downloads/valgrind-3.11.0.tar.bz2
tar -jxvf valgrind-3.11.0.tar.bz2
cd valgrind-3.11.0; ./autogen.sh
mkdir /usr/local/valgrind/ && ./configure --prefix=/usr/local/valgrind
make && make install
vim /etc/profile
export USE_ZEND_ALLOC=0

//php-cli
valgrind --leak-check=full php test.php

//php-fpm
vim 
# php_fpm_BIN=${exec_prefix}/sbin/php-fpm
export USE_ZEND_ALLOC=0
php_fpm_BIN="valgrind --log-file=/var/valgrind-%p.log /usr/local/php/sbin/php-fpm"

/usr/local/php/sbin/init.d.php-fpm restart
tail -f valgrind*

USE_ZEND_ALLOC是PHP提供的hook,我们可以在启动PHP前指定USE_ZEND_ALLOC=0,关闭内存管理功能。这样所有的内存分配都会直接向操作系统申请,这样valgrind就可以帮助我们定位问题。

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP试用MessagePackNext article:ColaPHP2.0的一些想法