PHP exec in background using & doesn't work
I am using this code on Ubuntu 13.04,
$cmd = "sleep 20 &> /dev/null &";
exec($cmd, $output);
Although it does sit there for 20 seconds and wait: / it usually works fine when used &
to send a process to the background, but on this machine php just won't do it: /
What could be causing this?
source to share
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've tested it for this. Here you start the php process first and then you do your task.
Or if pcntl module is not available use:
<?PHP
$cmd = "sleep 20 &> /dev/null &";
exec('/bin/bash -c "' . addslashes($cmd) . '"');
source to share
REASON does not work, as it exec()
executes the line you jump to. Since it is &
interpreted by the shell as "running in the background", but you are not executing the shell in your call exec
, &
it is just passed along with 20
to the executable /bin/sleep
- which is probably just ignoring this.
The same goes for output redirection as this is also parsed by the shell and not exec.
So, you either need to find a way to fork your process (as described above) or a way to run a subprocess as a shell.
source to share
My workaround for this on ubuntu 13.04 with Apache2 and any PHP version:, libssh2-php
I just used nohup $cmd &
inside a local SSH session using PHP and it just started it, of course, this requires setting certain security protocols like enabling SSH access for webserver user, so have exec-like rights and then allow localhost to log into the server's ssh account.
source to share