Last active
August 29, 2015 13:56
-
-
Save wwestenbrink/9204141 to your computer and use it in GitHub Desktop.
PHP wrapper script streaming stdout & stderr in parallel
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 | |
// 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