If it "doesn't care about the output", couldn't the exec to the script be called with the &
to background the process?
EDIT - incorporating what @AdamTheHut commented to this post, you can add this to a call to exec
:
" > /dev/null 2>/dev/null &"
That will redirect both stdio
(first >
) and stderr
(2>
) to /dev/null
and run in the background.
There are other ways to do the same thing, but this is the simplest to read.
An alternative to the above double-redirect:
" &> /dev/null &"
I used at for this, as it is really starting an independent process.
<?php
`echo "the command"|at now`;
?>
To all Windows users: I found a good way to run an asynchronous PHP script (actually it works with almost everything).
It's based on popen() and pclose() commands. And works well both on Windows and Unix.
function execInBackground($cmd) {
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
exec($cmd . " > /dev/null &");
}
}
Original code from: http://php.net/manual/en/function.exec.php#86329
On linux you can do the following:
$cmd = 'nohup nice -n 10 php -f php/file.php > log/file.log & printf "%u" $!';
$pid = shell_exec($cmd);
This will execute the command at the command prompty and then just return the PID, which you can check for > 0 to ensure it worked.
This question is similar: Does PHP have threading?
php-execute-a-background-process has some good suggestions. I think mine is pretty good, but I'm biased :)
In Linux, you can start a process in a new independent thread by appending an ampersand at the end of the command
mycommand -someparam somevalue &
In Windows, you can use the "start" DOS command
start mycommand -someparam somevalue
the right way(!) to do it is to
fork forks, setsid tell the current process to become a master one (no parent), execve tell the calling process to be replaced by the called one. so that the parent can quit without affecting the child.
$pid=pcntl_fork();
if($pid==0)
{
posix_setsid();
pcntl_exec($cmd,$args,$_ENV);
// child becomes the standalone detached process
}
// parent's stuff
exit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With