Skip to content

Instantly share code, notes, and snippets.

@moriyoshi
Created February 12, 2012 09:51
Show Gist options
  • Save moriyoshi/1807548 to your computer and use it in GitHub Desktop.
Save moriyoshi/1807548 to your computer and use it in GitHub Desktop.
<?php
$number_of_workers = 5;
$children = array();
$pair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_DGRAM, STREAM_IPPROTO_IP);
stream_set_blocking($pair[0], 0);
stream_set_blocking($pair[1], 0);
function do_work($fd) {
$pid = getmypid();
for ($i = 0; $i < 10; $i++) {
if ($i % 3 == 0)
fwrite($fd, "$pid;fizz");
if ($i % 5 == 0)
fwrite($fd, "$pid;buzz");
sleep(mt_rand(10, 500) / 100);
}
}
for ($i = 0; $i < $number_of_workers; $i++) {
if (($pid = pcntl_fork()) == 0) {
fclose($pair[0]);
do_work($pair[1]);
exit();
} else {
echo "Launched child (pid=$pid)\n";
$children[] = $pid;
}
}
while (pcntl_waitpid(-1, $status, WNOHANG) == 0) {
$rfds = array($pair[0]);
$nfds = stream_select($rfds, $wfds = null, $efds = null, 1);
foreach ($rfds as $rfd) {
var_dump(fread($rfd, 1024));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment