这个PHP代码片段中的内存泄漏在哪里?

时间:2013-02-22 18:15:26

标签: php memory-leaks

我有一个PHP代码段,可以读取apache访问日志以进行处理。我已经将代码删除到这几行,我仍然发现泄漏。即使echo memory_get_usage()每次都报告11Mb,PHP进程也会占用越来越多的内存。

在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

任何内存泄漏可能存在的想法?以及如何避免它?

1 个答案:

答案 0 :(得分:0)

默认情况下,PHP不进行垃圾收集(似乎是从手册中略过)。你可以做几件事。

1)使用gc_enable()启用GC。您可以使用gc_collect_cycles()强制执行GC传递。

2)使用$line明确销毁unset($line)