views:

107

answers:

1

What are the downsides to running a forked PHP app on the web?

I have read that it should not be run under Apache for any reason, but never explained why.
The only reason I can think of is that if a script is terminated in the middle of execution, any forked process would never be terminated and might cause memory leaks.

The question is in regards to the pcntl extensions

<?php
$pid = pcntl_fork();
if ($pid)
{
  //parent, execute parent code
}
else
{
  //child code
}
?>

Am I correct in this assumption?

+3  A: 

Calling fork() from an Apache server process (and then NOT exec'ing) is a really bad idea.

The main problem is that file descriptors will still be shared with the parent, which means that things like database connections and sockets will be shared in an un-useful way.

Instead of using fork(), then just spawn a separate process - if you want to run PHP, run the PHP command-line executable to run the script to do whatever you want to do.

Otherwise you'll cause Apache to do bad things - for example, if the parent process then serves more requests on the same connection, and your forked process happens to send some output, it'll get interleaved at arbitrary points in the response - which will generate seemingly random hard-to-diagnose errors. Things work even less well if the connection is SSL (The SSL session will contain errors and be terminated unexpectedly, creating some weird browser errors in my experience).

While fork() seems convenient, it's simply not worth the risk. It doesn't work in the general case.

MarkR