note 35777 added to ref.pcntl
| From: | David at rn2 dot php dot net | Date: | Sun, 14 Sep 2003 17:32:17 +0000 |
| Subject: | note 35777 added to ref.pcntl | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-56473@lists.php.net to get a copy of this message | ||
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...
----
Manual Page -- http://www.php.net/manual/en/ref.pcntl.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35777
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35777&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35777&report=yes