Skip to content

Instantly share code, notes, and snippets.

@wwestenbrink
Last active August 29, 2015 13:56
Show Gist options
  • Save wwestenbrink/9204141 to your computer and use it in GitHub Desktop.
Save wwestenbrink/9204141 to your computer and use it in GitHub Desktop.
PHP wrapper script streaming stdout & stderr in parallel
<?php
// microsecond timeout
$timeout = 1000;
// launch proces, retrieve output & error streams
$proc=proc_open($cmd,array(0=>array('pipe','r'),1=>array('pipe','w'),2=>array('pipe','w')), $streams);
$stdOut = $streams[1];
$stdErr = $streams[2];
while($stdOut || $stdErr){
$streams = array();
// only read from open streams
if ($stdOut)
$streams[] = $stdOut;
if ($stdErr)
$streams[] = $stdErr;
// check if there are any streams left to read from
if (empty($streams)) break;
// wait for output from open streams
if (false !== stream_select($streams, $write=null, $expect=null, 0, $timeout)) {
// $streams now contains available streams
foreach($streams as $stream) {
if($stream == $stdOut) {
// read one line from output stream
$line = fgets($stdOut );
if (trim($line))
echo "Out: $line";
if (feof($stdOut)) {
echo "Closing output stream\n";
fclose($stdOut);
$stdOut = null;
}
}
if($stream == $stdErr) {
// read one line from error stream
$line = fgets($stdErr);
if (trim($line))
echo "Error: $line";
if (feof($stdErr)) {
echo "Closing error stream\n";
fclose($stdErr);
$stdErr = null;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment