Skip to content

Instantly share code, notes, and snippets.

@CHH
Created May 30, 2012 06:13
Show Gist options
  • Save CHH/2834058 to your computer and use it in GitHub Desktop.
Save CHH/2834058 to your computer and use it in GitHub Desktop.
Einhorn PHP Example
<?php
declare(ticks = 1);
# Einhorn sends a "USR2" signal to our server process
# in case the server shuts down.
pcntl_signal(SIGUSR2, function() {
fwrite(STDERR, "Worker shutting down...\n");
exit(0);
});
# Einhorn passes the file descriptor number as first argument
# to the script.
$fd = $argv[1];
# The "php://fd" stream is a hidden gem, and can be used
# to connect to an already open file descriptor by its number.
$server = fopen("php://fd/$fd", "rb");
if (false === $server) {
exit(1);
}
stream_set_blocking($server, 0);
for (;;) {
$read = array($server);
$write = null;
$except = array($server);
$ready = stream_select($read, $write, $except, 0, 5E5);
if ($ready > 0) {
if ($read) {
handleConnection($read[0]);
}
if ($except) {
exit(1);
}
}
}
function handleConnection($server)
{
$client = stream_socket_accept($server);
if (false === $client) {
return;
}
$body = "Hello World!\n";
$headers = array(
"Content-Type: text/html",
"Content-Length: " . strlen($body),
"Connection: close"
);
fwrite($client, "HTTP/1.1 200 OK\r\n");
fwrite($client, join("\r\n", $headers));
fwrite($client, "\r\n\r\n");
fwrite($client, $body);
fclose($client);
}
#!/usr/bin/env bash
# Launches 4 instances of our server script, opens
# a socket on 127.0.0.1:1337 and passes the number
# of the file descriptor to our "server.php" as first argument.
einhorn -n 4 php server.php srv:127.0.0.1:1337
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment