如何通过吃掉所有可用的内存并最终使笔记本电脑崩溃来阻止php中的无限递归函数?

I have a simple infinite recursive code here:

        <?php

        function test(){
             test();
        }
        test();

When I try to run the same, it eats up all the memory and eventually my laptop hangs. What I am looking for is a way to catch this and stop the machine from hanging. Is there any Error handler in php for the same?

Things I have read and tried: setting max_execution_time to lets say 5 secs and catch the error line no. This dint work as proposed.

Any other way to catch and stop this?

If you need to limit the memory (rather than the CPU time) eaten up by your php process, see this question.

If you specifically want to limit the number of recursive call levels you allow... that's a different question, and I don't know of a way. But I'm surprised this would be a problem, because according to this question, PHP already has a 100-level recursion limit which should be enough to stop your script before it eats up significant memory.

Limit the shell subprocess memory usage:

̃Since you state you use Ubuntu you can limit the memory your processes.

$ 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

From php you can set the configutation option 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

Now you can also edit the memory_limit in the default php.ini or you can make a specific one for your script.

$ 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

You might want to copy the default one instead of having one just provifing that one option.

<?php

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