|
12 | 12 | use function array_merge;
|
13 | 13 | use function fclose;
|
14 | 14 | use function file_put_contents;
|
| 15 | +use function fread; |
15 | 16 | use function fwrite;
|
16 | 17 | use function is_array;
|
17 | 18 | use function is_resource;
|
18 | 19 | use function proc_close;
|
19 | 20 | use function proc_open;
|
20 |
| -use function stream_get_contents; |
| 21 | +use function proc_terminate; |
| 22 | +use function sprintf; |
| 23 | +use function stream_select; |
21 | 24 | use function sys_get_temp_dir;
|
22 | 25 | use function tempnam;
|
23 | 26 | use function unlink;
|
@@ -112,16 +115,64 @@ protected function runProcess(string $job, array $settings): array
|
112 | 115 |
|
113 | 116 | $stderr = $stdout = '';
|
114 | 117 |
|
115 |
| - if (isset($pipes[1])) { |
116 |
| - $stdout = stream_get_contents($pipes[1]); |
| 118 | + unset($pipes[0]); |
| 119 | + $timeout = 5; |
117 | 120 |
|
118 |
| - fclose($pipes[1]); |
119 |
| - } |
| 121 | + while (true) { |
| 122 | + $r = $pipes; |
| 123 | + $w = null; |
| 124 | + $e = null; |
| 125 | + |
| 126 | + $n = @stream_select($r, $w, $e, $timeout); |
| 127 | + |
| 128 | + if ($n === false) { |
| 129 | + break; |
| 130 | + } |
| 131 | + |
| 132 | + if ($n === 0) { |
| 133 | + proc_terminate($process, 9); |
| 134 | + |
| 135 | + throw new PhpProcessException( |
| 136 | + sprintf( |
| 137 | + 'Job execution aborted after %d seconds', |
| 138 | + $timeout, |
| 139 | + ), |
| 140 | + ); |
| 141 | + } |
120 | 142 |
|
121 |
| - if (isset($pipes[2])) { |
122 |
| - $stderr = stream_get_contents($pipes[2]); |
| 143 | + if ($n > 0) { |
| 144 | + foreach ($r as $pipe) { |
| 145 | + $pipeOffset = 0; |
123 | 146 |
|
124 |
| - fclose($pipes[2]); |
| 147 | + foreach ($pipes as $i => $origPipe) { |
| 148 | + if ($pipe === $origPipe) { |
| 149 | + $pipeOffset = $i; |
| 150 | + |
| 151 | + break; |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + if (!$pipeOffset) { |
| 156 | + break; |
| 157 | + } |
| 158 | + |
| 159 | + $line = fread($pipe, 8192); |
| 160 | + |
| 161 | + if ($line === '' || $line === false) { |
| 162 | + fclose($pipes[$pipeOffset]); |
| 163 | + |
| 164 | + unset($pipes[$pipeOffset]); |
| 165 | + } elseif ($pipeOffset === 1) { |
| 166 | + $stdout .= $line; |
| 167 | + } else { |
| 168 | + $stderr .= $line; |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + if (empty($pipes)) { |
| 173 | + break; |
| 174 | + } |
| 175 | + } |
125 | 176 | }
|
126 | 177 |
|
127 | 178 | proc_close($process);
|
|
0 commit comments