BashExecutor.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Libs;
  3. class BashExecutor
  4. {
  5. public static function run(string $command, int $timeoutSeconds = 30): array
  6. {
  7. $descriptorSpec = [
  8. 0 => ["pipe", "r"], // STDIN
  9. 1 => ["pipe", "w"], // STDOUT
  10. 2 => ["pipe", "w"] // STDERR
  11. ];
  12. $process = proc_open($command, $descriptorSpec, $pipes);
  13. if (!is_resource($process)) {
  14. return [
  15. "exitCode" => -1,
  16. "output" => "",
  17. "error" => "Failed to start process"
  18. ];
  19. }
  20. // Timeout handling
  21. $start = time();
  22. $stdout = "";
  23. $stderr = "";
  24. do {
  25. $status = proc_get_status($process);
  26. $stdout .= stream_get_contents($pipes[1]);
  27. $stderr .= stream_get_contents($pipes[2]);
  28. usleep(100000); // 0.1 segundo
  29. if ((time() - $start) > $timeoutSeconds) {
  30. proc_terminate($process);
  31. return [
  32. "exitCode" => -1,
  33. "output" => $stdout,
  34. "error" => "Timeout of {$timeoutSeconds}s reached"
  35. ];
  36. }
  37. } while ($status['running']);
  38. foreach ($pipes as $pipe) {
  39. fclose($pipe);
  40. }
  41. $exitCode = proc_close($process);
  42. return [
  43. "exitCode" => $exitCode,
  44. "output" => trim($stdout),
  45. "error" => trim($stderr)
  46. ];
  47. }
  48. }