Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
This was written by Russell Beattie; I copied it here from a pastebin to give it a permanent home.
Simple preforking echo server in PHP.
Russell Beattie (
PHP port of
/* Allow the script to hang around waiting for connections. */
# Create a socket, bind it to localhost:4242, and start
# listening. Runs once in the parent; all forked children
# inherit the socket's file descriptor.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket,'localhost', 4242);
socket_listen($socket, 10);
pcntl_signal(SIGTERM, 'shutdown');
pcntl_signal(SIGINT, 'shutdown');
function shutdown($signal){
global $socket;
# Fork you some child processes. In the parent, the call to
# fork returns immediately with the pid of the child process;
# fork never returns in the child because we exit at the end
# of the block.
for($x = 1; $x <= 3; $x++){
$pid = pcntl_fork();
# pcntl_fork() returns 0 in the child process and the child's
# process id in the parent. So if $pid == 0 then we're in
# the child process.
if($pid == 0){
$childpid = posix_getpid();
echo "Child $childpid listening on localhost:4242 \n";
# This is where the magic happens. accept(2)
# blocks until a new connection is ready to be
# dequeued.
$conn = socket_accept($socket);
$message = socket_read($conn,1000,PHP_NORMAL_READ);
socket_write($conn, "Child $childpid echo> $message");
echo "Child $childpid echo'd: $message \n";
# Trap interrupts, write a note, and exit immediately in
# parent. This trap is not inherited by the forks because it
# runs after forking has commenced.
pcntl_waitpid(-1, $status);
} catch (Exception $e) {
echo "bailing \n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment