简体   繁体   中英

PHP exec in background using & is not working

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

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) . '"');

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM