PHP exec in background using & is not working

不羁的心 提交于 2020-01-13 14:04:13

问题


I am using this code on Ubuntu 13.04,

$cmd = "sleep 20 &> /dev/null &";
exec($cmd, $output);

Although it actually sits there for 20 seconds and waits :/ usually it works fine when using & to send a process to the background, but on this machine php just won't do it :/
What could be causing this??


回答1:


Try

<?PHP
$cmd = '/bin/sleep';
$args = array('20');

$pid=pcntl_fork();
if($pid==0)
{
  posix_setsid();
  pcntl_exec($cmd,$args,$_ENV);
  // child becomes the standalone detached process
}

echo "DONE\n";

I tested it for it works. Here you first fork the php process and then exceute your task.

Or if the pcntl module is not availabil use:

<?PHP

$cmd = "sleep 20 &> /dev/null &";
exec('/bin/bash -c "' . addslashes($cmd) . '"');



回答2:


The REASON this doesn't work is that exec() executes the string you're passing into it. Since & is interpreted by the shell as "execute in the background", but you don't execute a shell in your exec call, the & is just passed along with 20 to the /bin/sleep executable - which probably just ignores that.

The same applies to the redirection of output, since that is also parsed by the shell, not in exec.

So, you either need to find a way to fork your process (as described above), or a way to run the subprocess as a shell.




回答3:


My workaround to do this on ubuntu 13.04 with Apache2 and any version of PHP:
libssh2-php, I just used nohup $cmd & inside a local SSH session using PHP and it ran it just fine the background, of course this requires putting certain security protocols in place, such as enabling SSH access for the webserver user, so it would have exec-like permissions then only allowing localhost to login to the webserver ssh account.



来源:https://stackoverflow.com/questions/14412190/php-exec-in-background-using-is-not-working

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