how to use pcntl_fork() with Apache?
Asked Answered
G

2

5

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?

Godforsaken answered 31/8, 2012 at 11:50 Comment(1)
G
2

This is the solution:

posix_kill(getmypid(), SIGKILL);

instead of exit().

Godforsaken answered 5/9, 2012 at 8:38 Comment(1)
The correct solution is to use pcntl_wait in the parent and writ for the child rpocesses to finish to avoid zombies. The suggested solution might or might not work, depending on the signal handlers of the children, also it's not really "healthy" to SIGKILL a process in a production code as you can't isntall signal hanler on SIGKILL and so you might leave resources hanging in the air or leave the program in an inconsistent state.Smalltime
A
5

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()'

Algoid answered 31/8, 2012 at 11:52 Comment(2)
you're referring to a comment at php.net, not part of an official documentation. pcntl_fork() does work in apache, but doesn't create a normal standalone process, I guess.Godforsaken
you should install pcntl extension thenGodforsaken
G
2

This is the solution:

posix_kill(getmypid(), SIGKILL);

instead of exit().

Godforsaken answered 5/9, 2012 at 8:38 Comment(1)
The correct solution is to use pcntl_wait in the parent and writ for the child rpocesses to finish to avoid zombies. The suggested solution might or might not work, depending on the signal handlers of the children, also it's not really "healthy" to SIGKILL a process in a production code as you can't isntall signal hanler on SIGKILL and so you might leave resources hanging in the air or leave the program in an inconsistent state.Smalltime

© 2022 - 2024 — McMap. All rights reserved.