I had a hard time finding a complete example of using PHP as a multi-process (or multi-threaded - I don't understand the difference in these two terms) daemon using connection pooling. I put pieces of the puzzle together and came up with the program below. I hope it helps someone. Notes about making this work:
1) I rebuilt PHP on my machine with these config options:
./configure --enable-sockets --enable-pcntl --enable-sigchild
make
make install
2) I have problems when tried to handle SIGTERM and SIGHUP myself, so I removed these from my code, don't use them unless you have a special need for this:
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
What I do is:
1. start the program, then fork to detach from the terminal (kill the parent and make the child the session leader).
2. bind to address and port and start listening.
3. fork $poolNum times, creating $poolNum children (this is the pool of daemons running. The children handle the incoming connections).
4. keep the parent process running in a loop, constantly checking to see if it should create a new child. It will always keep $poolNum spare children ready (as long as the total pooled connections doesn't exceed $maxDaemon). As connections come in, more children are spawned.
5. When a new connection comes in, it is handed off to the first child. This child then sends a SIGUSR1 signal back to the parent. The parent has a signal handler for SIGUSR1, which will increment the $numActive variable by one. The loop that is running (see 4 above) will note the increment in $numActive and automatically create a new child process to keep the process pool going.
I have to post the code in the next note, the note engine on this site won't allow such a long note to be posted, but I think this code example is well worth a comment on this...