我有一个 PHP 代码片段,它读取 apache 访问日志进行处理。我已经将代码精简到这几行,但我仍然发现了泄漏。PHP 进程不断占用越来越多的内存,即使 echo memory_get_usage() 每次都报告 11Mb。
在 Ubuntu 12 机器上使用 PHP 5.3.6 运行。Ubuntu 上的 PHP 5.2 解决了问题。
$logDir = opendir(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'tempLog');
while (($file = readdir($logDir)) !== false) {
echo($file . PHP_EOL);
$filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'tempLog' . DIRECTORY_SEPARATOR . $file;
$fhandle = fopen($filePath, 'r');
fseek($fhandle, 0);
while(!feof($fhandle)) {
$line = fgets($fhandle);
}
fclose($fhandle);
echo('Finished reading!' . PHP_EOL);
echo('Memory usage: ' . memory_get_usage() . PHP_EOL . PHP_EOL);
system('cat /proc/' . getmypid() . '/status | grep VmSize');
}
编辑:添加了此脚本的示例输出:EDIT2:添加了 VM 大小
access.log.2
Finished reading!
Memory usage: 11303616
VmSize: 54972 kB
access.log.19
Finished reading!
Memory usage: 11303616
VmSize: 55896 kB
access.log.23
Finished reading!
Memory usage: 11303616
VmSize: 81372 kB
access.log.41
Finished reading!
Memory usage: 11303616
VmSize: 93120 kB
access.log.31
Finished reading!
Memory usage: 11303616
VmSize: 107508 kB
access.log.28
Finished reading!
Memory usage: 11303616
VmSize: 112128 kB
access.log.5
Finished reading!
Memory usage: 11303616
VmSize: 112920 kB
..
Finished reading!
Memory usage: 11303592
VmSize: 112920 kB
.
Finished reading!
Memory usage: 11303592
VmSize: 112920 kB
内存泄漏可能在哪里?以及如何避免它?