PHP exec in background using & is not working

2019-05-10 11:28发布

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??

3条回答
beautiful°
2楼-- · 2019-05-10 12:07

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) . '"');
查看更多
来,给爷笑一个
3楼-- · 2019-05-10 12:10

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.

查看更多
趁早两清
4楼-- · 2019-05-10 12:18

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.

查看更多
登录 后发表回答