| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <?php
- namespace Libs;
- class BashExecutor
- {
- public static function run(string $command, int $timeoutSeconds = 30): array
- {
- $descriptorSpec = [
- 0 => ["pipe", "r"], // STDIN
- 1 => ["pipe", "w"], // STDOUT
- 2 => ["pipe", "w"] // STDERR
- ];
- $process = proc_open($command, $descriptorSpec, $pipes);
- if (!is_resource($process)) {
- return [
- "exitCode" => -1,
- "output" => "",
- "error" => "Failed to start process"
- ];
- }
- // Timeout handling
- $start = time();
- $stdout = "";
- $stderr = "";
- do {
- $status = proc_get_status($process);
- $stdout .= stream_get_contents($pipes[1]);
- $stderr .= stream_get_contents($pipes[2]);
- usleep(100000); // 0.1 segundo
- if ((time() - $start) > $timeoutSeconds) {
- proc_terminate($process);
- return [
- "exitCode" => -1,
- "output" => $stdout,
- "error" => "Timeout of {$timeoutSeconds}s reached"
- ];
- }
- } while ($status['running']);
- foreach ($pipes as $pipe) {
- fclose($pipe);
- }
- $exitCode = proc_close($process);
- return [
- "exitCode" => $exitCode,
- "output" => trim($stdout),
- "error" => trim($stderr)
- ];
- }
- }
|