开发者

PHP forking php-fpm with pcntl_fork()

I'm forking with this code:

echo "1. posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";

$pid = pcntl_fork();
var_dump($pid);
if ($pid == -1) die("could not fork");

if ($pid) {
//parent
echo "2. pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";
} else {
//child
$sid = posix_setsid();

if ($sid < 0)
exit;

echo "3. pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";

$fp = fopen("/tmp/testfile", "w");
fwrite($fp, '$data');
fclose($fp);

} 

For some reason sometimes the else block is sent to the browser, and sometimes the if ($pid) block is displayed.

What I'm trying to achieve is to send some response, and then continue processing after the connection with the client has closed. Then finally close after the post-request processing is finished. If I sleep in the child or parent the request hangs there.

Both parts are being executed though, it's just being weird in determining w开发者_StackOverflow社区hich on is sent to the browser.

Thanks in advance.


Actually you should use fastcgi_finish_request() to send the response to the browser, then continue working in the background. Keep in mind though, that this ONLY works when using PHP-FPM.

Note: the fastcgi_finish_request() function isn't documented in the PHP manual (see bug 61449) but the usage is pretty straight forward.

As for ignore_user_abort(), some comments on php.net suggest using the Content-Length: 0 header with it, but this will cause problems when using SSL in conjunction with Internet Explorer.


Consider using ignore_user_abort() instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜