如何阻止 PHP 中的无限递归函数消耗所有可用内存并最终导致笔记本电脑崩溃



我这里有一个简单的无限递归代码:

<?php
    function test() {
        test();
    }
    test();

当我尝试运行相同的程序时,它会占用所有内存,最终我的笔记本电脑挂起。我正在寻找一种抓住它并阻止机器挂起的方法。PHP 中是否有相同的错误处理程序

我已经阅读并尝试过的事情:将max_execution_time设置为,比方说,5秒并捕获错误行号。这没有按照建议工作。

有没有其他方法可以抓住并阻止这种情况?

我正在使用Ubuntu 16.04.1 LTS(Xenial Xerus(。

限制 shell 子进程内存使用量:

由于您声明使用 Ubuntu,因此您可以限制进程的内存:

$ ulimit -v 500000
$ php -r 'function test() { test(); } test();'
mmap() failed: [12] Cannot allocate memory
mmap() failed: [12] Cannot allocate memory
PHP Fatal error:  Out of memory (allocated 304087040) (tried to allocate 262144 bytes) in Command line code on line 1

从 PHP 中,您可以将配置选项设置为memory_limit

$ php -r 'ini_set("memory_limit", "500MB"); function test() { test(); } test();'
PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 262144 bytes) in Command line code on line 1

现在,您还可以在默认的 php.ini 文件中编辑memory_limit,也可以为您的脚本创建一个特定的文件。

$ echo 'memory_limit = 500MB' > test.ini
$ php --php-ini test.ini -r 'function test() { test(); } test();'
Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 262144 bytes) in Command line code on line 1

您可能希望复制默认选项,而不是仅提供该选项。

<?php
    function test($tryCount=1){
         $tryCount++;
         //terminate recursive if more than 10 times loop
         if($tryCount > 10){
             return false;
         }
         test($tryCount);
    }
    test();

如果您需要限制 PHP 进程占用的内存(而不是 CPU 时间(,请参阅此问题。

如果您特别想要限制允许的递归调用级别的数量...这是一个不同的问题,我不知道有什么办法。但我很惊讶这将是一个问题,因为根据这个问题,PHP 已经有一个 100 级递归限制,这应该足以在脚本占用大量内存之前停止它。

最新更新