|
Posted by Andy Jeffries on 04/24/06 21:59
On Mon, 24 Apr 2006 14:50:24 +0000, Andy Jeffries wrote:
> I've got a script which calls (via exec) "php myscript.php --params=here".
>
> Within myscript.php I try to become a daemon (to continue asynchronously
> from the calling script) using pcntl_fork, posix_setsid and pcntl_fork
> again.
>
> It works if I call the myscript.php from the command line (it correctly
> damonises and returns immediately, carrying on processing in the
> background), but when I do it through Apache (request the calling
> script) it waits for the child to complete first.
OK, I found out the problem. My "become daemon" function didn't close
stdout, so Apache always waited on stdout EOFing even though the process
went in to the background.
Fixed now.
For anyone interested, a working function to become a Daemon (background
task, unattached from the parent process) from a PHP CLI script is:
function become_daemon()
{
$pid = pcntl_fork();
if ($pid == 1) {
die("Could not fork");
}
else if ($pid) {
exit; // Parent process should exit nicely
}
$detach = posix_setsid();
if (!$detach) {
die("Could not detach");
}
if (pcntl_fork())
exit;
$stdout = fopen("php://stdout", "w");
fclose($stdout);
// Now we're a daemon
}
Cheers,
Andy
--
Andy Jeffries MBCS CITP ZCE | gPHPEdit Lead Developer
http://www.gphpedit.org | PHP editor for Gnome 2
http://www.andyjeffries.co.uk | Personal site and photos
Navigation:
[Reply to this message]
|