shell_exec causes infinite loop

淺唱寂寞╮ 提交于 2021-01-29 02:11:58

问题


I have a problem with shell_exec. I try to run the other php file in a separate thread, according to this answer: https://stackoverflow.com/a/222445/1999929 I have this very-very simple code:

<?php
     $realpath = realpath("./second.php");
     file_put_contents("./log.txt","\nFirst php running!\n",FILE_APPEND);
     shell_exec("php $realpath > /dev/null 2>/dev/null &");
?>

I need this because i want to use this file for a dropbox webhook link, and it has to give a response in 10 seconds, while processing the changed files sometimes takes more time. So this file has to tell te other to run, and give a response, while not waiting for the other to finish.

When shell_exec is used in the code, the text is outputted infinite times in the file, without it its working fine, but i need to call the other file somehow.

EDIT - I tried exec() too, because the answer above used it instead of shell_exec, results are the same.


回答1:


The issue is with the ENV, something in the ENV conflict with the second call to PHP making PHP calling infinite times the second file. This will create a fork bomb.

But if you just reset the $env array to an empty array the second file will be called correctly.

Neither shell_exec() or exec() all you to manipulate $ENV. You'll need to use "proc_open":

resource proc_open ( $cmd , $descriptorspec , &$pipes [, $cwd [, $env]] )

So:

<?php
     $env = array();
     $realpath = realpath("./second.php");
     file_put_contents("./log.txt","\nFirst php running!\n",FILE_APPEND);
     proc_open(
        "php $realpath > /dev/null 2>/dev/null &",
        $descriptorspec,
        $pipes,
        __DIR__,
        $env
     );
?>



回答2:


This bug affect only the CGI version of PHP, the CGI module replace the command called with the script itself causing infinite loop.

In order to prevent this you should call "php-cli" instead of "php":

shell_exec("php-cli $realpath > /dev/null 2>/dev/null &");


来源:https://stackoverflow.com/questions/25437789/shell-exec-causes-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!