ProcessTestHelper.php 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, false);
  9. stream_set_blocking(STDOUT, false);
  10. stream_set_blocking(STDERR, false);
  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. {
  24. $written = fwrite(STDOUT, (binary) $out, 1024);
  25. if (false === $written) {
  26. die(ERR_WRITE_FAILED);
  27. }
  28. $out = (binary) substr($out, $written);
  29. }
  30. if (null === $read && strlen($out) < 1) {
  31. $write = array_diff($write, array(STDOUT));
  32. }
  33. if (in_array(STDERR, $w) && strlen($err) > 0)
  34. {
  35. $written = fwrite(STDERR, (binary) $err, 1024);
  36. if (false === $written) {
  37. die(ERR_WRITE_FAILED);
  38. }
  39. $err = (binary) substr($err, $written);
  40. }
  41. if (null === $read && strlen($err) < 1) {
  42. $write = array_diff($write, array(STDERR));
  43. }
  44. if ($r) {
  45. $str = fread(STDIN, 1024);
  46. if (false !== $str) {
  47. $out .= $str;
  48. $err .= $str;
  49. }
  50. if (false === $str || feof(STDIN)) {
  51. $read = null;
  52. if (!feof(STDIN)) {
  53. die(ERR_READ_FAILED);
  54. }
  55. }
  56. }
  57. }