Last active
December 17, 2015 18:49
-
-
Save morozov/5655576 to your computer and use it in GitHub Desktop.
Trying to setup communication by means of STDIO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function start_worker($id) | |
{ | |
printf("starting worker: %s\n", $id); | |
$proc = proc_open( | |
'php worker.php ' . $id, | |
array( | |
array('pipe', 'r'), | |
array('pipe', 'w'), | |
array('file', '/dev/null', 'w'), | |
), | |
$pipes | |
); | |
return array($proc, $pipes); | |
} | |
function stop_worker($proc, array $pipes) | |
{ | |
fclose($pipes[0]); | |
fclose($pipes[1]); | |
fclose($pipes[2]); | |
proc_close($proc); | |
} | |
function get_workers($count) | |
{ | |
$workers = array(); | |
for ($i = 1; $i <= $count; $i++) { | |
$workers[$i] = start_worker($i); | |
} | |
return $workers; | |
} | |
$workers = get_workers(4); | |
$tasks = range(1, 10); | |
$working = array(); | |
$write_pool = array(); | |
$read_pool = array(); | |
foreach ($workers as $id => $worker) { | |
list(,$pipes) = $worker; | |
$write_pool[$id] = $pipes[0]; | |
$read_pool[$id] = $pipes[1]; | |
} | |
while ($tasks || $working) { | |
$read = array_intersect_key($read_pool, $working); | |
$write = array_diff_key($write_pool, $working); | |
$except = null; | |
$ready = stream_select($read, $write, $except, 1); | |
if (!$ready) { | |
break; | |
} | |
while ($write && $tasks) { | |
$stream = array_shift($write); | |
$task = array_shift($tasks); | |
fwrite($stream, $task . PHP_EOL); | |
$id = array_search($stream, $write_pool); | |
printf("delegated task: %s to %s\n", $task, $id); | |
$working[$id]= true; | |
} | |
while ($read) { | |
$stream = array_shift($read); | |
$result = fgets($stream); | |
$result = rtrim($result, PHP_EOL); | |
printf("got response: %s\n", $result); | |
$id = array_search($stream, $read_pool); | |
unset($working[$id]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ($_SERVER['argc'] > 1) { | |
$id = $_SERVER['argv'][1]; | |
} else { | |
$id = 'unknown'; | |
} | |
$fp = fopen('php://stdin', 'r'); | |
while (!feof($fp) && ($s = fgets($fp)) !== false) { | |
$s = rtrim($s, PHP_EOL); | |
$d = mt_rand(0, 1000000); | |
usleep($d); | |
$c = sprintf( | |
'%s (worker: %s, slept %d μs)' . PHP_EOL, | |
strrev($s), | |
$id, | |
$d | |
); | |
echo $c; | |
} | |
fclose($fp); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment