how to use pcntl_fork() with Apache?

2019-02-26 01:43发布

问题:

This is my code, inside index.php (just an example):

$pid = pcntl_fork();
if ($pid == -1) {
  die("failed to fork");
} else if ($pid) {
  // nothing to do
} else {
  putDataIntoWebService();
  exit();
}
echo "normal page content";

This snippet works fine in command line. In Apache exit() kills them both, the parent and the kid process. What is a workaround?

回答1:

You can't use the pcntl_* functions with the Apache module version of PHP. Quoting from a comment in the pcntl_fork documentation:

It is not possible to use the function 'pcntl_fork' when PHP is used as Apache module. You can only use pcntl_fork in CGI mode or from command-line.

Using this function will result in: 'Fatal error: Call to undefined function: pcntl_fork()'



回答2:

This is the solution:

posix_kill(getmypid(), SIGKILL);

instead of exit().



标签: php apache pcntl