PipeStdinInStdoutStdErrStreamSelect.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. define('ERR_SELECT_FAILED', 1);
  3. define('ERR_TIMEOUT', 2);
  4. define('ERR_READ_FAILED', 3);
  5. define('ERR_WRITE_FAILED', 4);
  6. $read = array(STDIN);
  7. $write = array(STDOUT, STDERR);
  8. stream_set_blocking(STDIN, 0);
  9. stream_set_blocking(STDOUT, 0);
  10. stream_set_blocking(STDERR, 0);
  11. $out = $err = '';
  12. while ($read || $write) {
  13. $r = $read;
  14. $w = $write;
  15. $e = null;
  16. $n = stream_select($r, $w, $e, 5);
  17. if (false === $n) {
  18. die(ERR_SELECT_FAILED);
  19. } elseif ($n < 1) {
  20. die(ERR_TIMEOUT);
  21. }
  22. if (in_array(STDOUT, $w) && strlen($out) > 0) {
  23. $written = fwrite(STDOUT, (binary) $out, 32768);
  24. if (false === $written) {
  25. die(ERR_WRITE_FAILED);
  26. }
  27. $out = (binary) substr($out, $written);
  28. }
  29. if (null === $read && strlen($out) < 1) {
  30. $write = array_diff($write, array(STDOUT));
  31. }
  32. if (in_array(STDERR, $w) && strlen($err) > 0) {
  33. $written = fwrite(STDERR, (binary) $err, 32768);
  34. if (false === $written) {
  35. die(ERR_WRITE_FAILED);
  36. }
  37. $err = (binary) substr($err, $written);
  38. }
  39. if (null === $read && strlen($err) < 1) {
  40. $write = array_diff($write, array(STDERR));
  41. }
  42. if ($r) {
  43. $str = fread(STDIN, 32768);
  44. if (false !== $str) {
  45. $out .= $str;
  46. $err .= $str;
  47. }
  48. if (false === $str || feof(STDIN)) {
  49. $read = null;
  50. if (!feof(STDIN)) {
  51. die(ERR_READ_FAILED);
  52. }
  53. }
  54. }
  55. }