Process.php
30.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
namespace think;
use think\process\exception\Failed as ProcessFailedException;
use think\process\exception\Timeout as ProcessTimeoutException;
use think\process\pipes\Pipes;
use think\process\pipes\Unix as UnixPipes;
use think\process\pipes\Windows as WindowsPipes;
use think\process\Utils;
class Process
{
const ERR = 'err';
const OUT = 'out';
const STATUS_READY = 'ready';
const STATUS_STARTED = 'started';
const STATUS_TERMINATED = 'terminated';
const STDIN = 0;
const STDOUT = 1;
const STDERR = 2;
const TIMEOUT_PRECISION = 0.2;
private $callback;
private $commandline;
private $cwd;
private $env;
private $input;
private $starttime;
private $lastOutputTime;
private $timeout;
private $idleTimeout;
private $options;
private $exitcode;
private $fallbackExitcode;
private $processInformation;
private $outputDisabled = false;
private $stdout;
private $stderr;
private $enhanceWindowsCompatibility = true;
private $enhanceSigchildCompatibility;
private $process;
private $status = self::STATUS_READY;
private $incrementalOutputOffset = 0;
private $incrementalErrorOutputOffset = 0;
private $tty;
private $pty;
private $useFileHandles = false;
/** @var Pipes */
private $processPipes;
private $latestSignal;
private static $sigchild;
/**
* @var array
*/
public static $exitCodes = [
0 => 'OK',
1 => 'General error',
2 => 'Misuse of shell builtins',
126 => 'Invoked command cannot execute',
127 => 'Command not found',
128 => 'Invalid exit argument',
// signals
129 => 'Hangup',
130 => 'Interrupt',
131 => 'Quit and dump core',
132 => 'Illegal instruction',
133 => 'Trace/breakpoint trap',
134 => 'Process aborted',
135 => 'Bus error: "access to undefined portion of memory object"',
136 => 'Floating point exception: "erroneous arithmetic operation"',
137 => 'Kill (terminate immediately)',
138 => 'User-defined 1',
139 => 'Segmentation violation',
140 => 'User-defined 2',
141 => 'Write to pipe with no one reading',
142 => 'Signal raised by alarm',
143 => 'Termination (request to terminate)',
// 144 - not defined
145 => 'Child process terminated, stopped (or continued*)',
146 => 'Continue if stopped',
147 => 'Stop executing temporarily',
148 => 'Terminal stop signal',
149 => 'Background process attempting to read from tty ("in")',
150 => 'Background process attempting to write to tty ("out")',
151 => 'Urgent data available on socket',
152 => 'CPU time limit exceeded',
153 => 'File size limit exceeded',
154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
155 => 'Profiling timer expired',
// 156 - not defined
157 => 'Pollable event',
// 158 - not defined
159 => 'Bad syscall',
];
/**
* 构造方法
* @param string $commandline 指令
* @param string|null $cwd 工作目录
* @param array|null $env 环境变量
* @param string|null $input 输入
* @param int|float|null $timeout 超时时间
* @param array $options proc_open的选项
* @throws \RuntimeException
* @api
*/
public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = [])
{
if (!function_exists('proc_open')) {
throw new \RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
}
$this->commandline = $commandline;
$this->cwd = $cwd;
if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DS)) {
$this->cwd = getcwd();
}
if (null !== $env) {
$this->setEnv($env);
}
$this->input = $input;
$this->setTimeout($timeout);
$this->useFileHandles = '\\' === DS;
$this->pty = false;
$this->enhanceWindowsCompatibility = true;
$this->enhanceSigchildCompatibility = '\\' !== DS && $this->isSigchildEnabled();
$this->options = array_replace([
'suppress_errors' => true,
'binary_pipes' => true,
], $options);
}
public function __destruct()
{
$this->stop();
}
public function __clone()
{
$this->resetProcessData();
}
/**
* 运行指令
* @param callback|null $callback
* @return int
*/
public function run($callback = null)
{
$this->start($callback);
return $this->wait();
}
/**
* 运行指令
* @param callable|null $callback
* @return self
* @throws \RuntimeException
* @throws ProcessFailedException
*/
public function mustRun($callback = null)
{
if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
}
if (0 !== $this->run($callback)) {
throw new ProcessFailedException($this);
}
return $this;
}
/**
* 启动进程并写到 STDIN 输入后返回。
* @param callable|null $callback
* @throws \RuntimeException
* @throws \RuntimeException
* @throws \LogicException
*/
public function start($callback = null)
{
if ($this->isRunning()) {
throw new \RuntimeException('Process is already running');
}
if ($this->outputDisabled && null !== $callback) {
throw new \LogicException('Output has been disabled, enable it to allow the use of a callback.');
}
$this->resetProcessData();
$this->starttime = $this->lastOutputTime = microtime(true);
$this->callback = $this->buildCallback($callback);
$descriptors = $this->getDescriptors();
$commandline = $this->commandline;
if ('\\' === DS && $this->enhanceWindowsCompatibility) {
$commandline = 'cmd /V:ON /E:ON /C "(' . $commandline . ')';
foreach ($this->processPipes->getFiles() as $offset => $filename) {
$commandline .= ' ' . $offset . '>' . Utils::escapeArgument($filename);
}
$commandline .= '"';
if (!isset($this->options['bypass_shell'])) {
$this->options['bypass_shell'] = true;
}
}
$this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
if (!is_resource($this->process)) {
throw new \RuntimeException('Unable to launch a new process.');
}
$this->status = self::STATUS_STARTED;
if ($this->tty) {
return;
}
$this->updateStatus(false);
$this->checkTimeout();
}
/**
* 重启进程
* @param callable|null $callback
* @return Process
* @throws \RuntimeException
* @throws \RuntimeException
*/
public function restart($callback = null)
{
if ($this->isRunning()) {
throw new \RuntimeException('Process is already running');
}
$process = clone $this;
$process->start($callback);
return $process;
}
/**
* 等待要终止的进程
* @param callable|null $callback
* @return int
*/
public function wait($callback = null)
{
$this->requireProcessIsStarted(__FUNCTION__);
$this->updateStatus(false);
if (null !== $callback) {
$this->callback = $this->buildCallback($callback);
}
do {
$this->checkTimeout();
$running = '\\' === DS ? $this->isRunning() : $this->processPipes->areOpen();
$close = '\\' !== DS || !$running;
$this->readPipes(true, $close);
} while ($running);
while ($this->isRunning()) {
usleep(1000);
}
if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
throw new \RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
}
return $this->exitcode;
}
/**
* 获取PID
* @return int|null
* @throws \RuntimeException
*/
public function getPid()
{
if ($this->isSigchildEnabled()) {
throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
}
$this->updateStatus(false);
return $this->isRunning() ? $this->processInformation['pid'] : null;
}
/**
* 将一个 POSIX 信号发送到进程中
* @param int $signal
* @return Process
*/
public function signal($signal)
{
$this->doSignal($signal, true);
return $this;
}
/**
* 禁用从底层过程获取输出和错误输出。
* @return Process
*/
public function disableOutput()
{
if ($this->isRunning()) {
throw new \RuntimeException('Disabling output while the process is running is not possible.');
}
if (null !== $this->idleTimeout) {
throw new \LogicException('Output can not be disabled while an idle timeout is set.');
}
$this->outputDisabled = true;
return $this;
}
/**
* 开启从底层过程获取输出和错误输出。
* @return Process
* @throws \RuntimeException
*/
public function enableOutput()
{
if ($this->isRunning()) {
throw new \RuntimeException('Enabling output while the process is running is not possible.');
}
$this->outputDisabled = false;
return $this;
}
/**
* 输出是否禁用
* @return bool
*/
public function isOutputDisabled()
{
return $this->outputDisabled;
}
/**
* 获取当前的输出管道
* @return string
* @throws \LogicException
* @throws \LogicException
* @api
*/
public function getOutput()
{
if ($this->outputDisabled) {
throw new \LogicException('Output has been disabled.');
}
$this->requireProcessIsStarted(__FUNCTION__);
$this->readPipes(false, '\\' === DS ? !$this->processInformation['running'] : true);
return $this->stdout;
}
/**
* 以增量方式返回的输出结果。
* @return string
*/
public function getIncrementalOutput()
{
$this->requireProcessIsStarted(__FUNCTION__);
$data = $this->getOutput();
$latest = substr($data, $this->incrementalOutputOffset);
if (false === $latest) {
return '';
}
$this->incrementalOutputOffset = strlen($data);
return $latest;
}
/**
* 清空输出
* @return Process
*/
public function clearOutput()
{
$this->stdout = '';
$this->incrementalOutputOffset = 0;
return $this;
}
/**
* 返回当前的错误输出的过程 (STDERR)。
* @return string
*/
public function getErrorOutput()
{
if ($this->outputDisabled) {
throw new \LogicException('Output has been disabled.');
}
$this->requireProcessIsStarted(__FUNCTION__);
$this->readPipes(false, '\\' === DS ? !$this->processInformation['running'] : true);
return $this->stderr;
}
/**
* 以增量方式返回 errorOutput
* @return string
*/
public function getIncrementalErrorOutput()
{
$this->requireProcessIsStarted(__FUNCTION__);
$data = $this->getErrorOutput();
$latest = substr($data, $this->incrementalErrorOutputOffset);
if (false === $latest) {
return '';
}
$this->incrementalErrorOutputOffset = strlen($data);
return $latest;
}
/**
* 清空 errorOutput
* @return Process
*/
public function clearErrorOutput()
{
$this->stderr = '';
$this->incrementalErrorOutputOffset = 0;
return $this;
}
/**
* 获取退出码
* @return null|int
*/
public function getExitCode()
{
if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
}
$this->updateStatus(false);
return $this->exitcode;
}
/**
* 获取退出文本
* @return null|string
*/
public function getExitCodeText()
{
if (null === $exitcode = $this->getExitCode()) {
return;
}
return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
}
/**
* 检查是否成功
* @return bool
*/
public function isSuccessful()
{
return 0 === $this->getExitCode();
}
/**
* 是否未捕获的信号已被终止子进程
* @return bool
*/
public function hasBeenSignaled()
{
$this->requireProcessIsTerminated(__FUNCTION__);
if ($this->isSigchildEnabled()) {
throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}
$this->updateStatus(false);
return $this->processInformation['signaled'];
}
/**
* 返回导致子进程终止其执行的数。
* @return int
*/
public function getTermSignal()
{
$this->requireProcessIsTerminated(__FUNCTION__);
if ($this->isSigchildEnabled()) {
throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}
$this->updateStatus(false);
return $this->processInformation['termsig'];
}
/**
* 检查子进程信号是否已停止
* @return bool
*/
public function hasBeenStopped()
{
$this->requireProcessIsTerminated(__FUNCTION__);
$this->updateStatus(false);
return $this->processInformation['stopped'];
}
/**
* 返回导致子进程停止其执行的数。
* @return int
*/
public function getStopSignal()
{
$this->requireProcessIsTerminated(__FUNCTION__);
$this->updateStatus(false);
return $this->processInformation['stopsig'];
}
/**
* 检查是否正在运行
* @return bool
*/
public function isRunning()
{
if (self::STATUS_STARTED !== $this->status) {
return false;
}
$this->updateStatus(false);
return $this->processInformation['running'];
}
/**
* 检查是否已开始
* @return bool
*/
public function isStarted()
{
return self::STATUS_READY != $this->status;
}
/**
* 检查是否已终止
* @return bool
*/
public function isTerminated()
{
$this->updateStatus(false);
return self::STATUS_TERMINATED == $this->status;
}
/**
* 获取当前的状态
* @return string
*/
public function getStatus()
{
$this->updateStatus(false);
return $this->status;
}
/**
* 终止进程
*/
public function stop()
{
if ($this->isRunning()) {
if ('\\' === DS && !$this->isSigchildEnabled()) {
exec(sprintf('taskkill /F /T /PID %d 2>&1', $this->getPid()), $output, $exitCode);
if ($exitCode > 0) {
throw new \RuntimeException('Unable to kill the process');
}
} else {
$pids = preg_split('/\s+/', `ps -o pid --no-heading --ppid {$this->getPid()}`);
foreach ($pids as $pid) {
if (is_numeric($pid)) {
posix_kill($pid, 9);
}
}
}
}
$this->updateStatus(false);
if ($this->processInformation['running']) {
$this->close();
}
return $this->exitcode;
}
/**
* 添加一行输出
* @param string $line
*/
public function addOutput($line)
{
$this->lastOutputTime = microtime(true);
$this->stdout .= $line;
}
/**
* 添加一行错误输出
* @param string $line
*/
public function addErrorOutput($line)
{
$this->lastOutputTime = microtime(true);
$this->stderr .= $line;
}
/**
* 获取被执行的指令
* @return string
*/
public function getCommandLine()
{
return $this->commandline;
}
/**
* 设置指令
* @param string $commandline
* @return self
*/
public function setCommandLine($commandline)
{
$this->commandline = $commandline;
return $this;
}
/**
* 获取超时时间
* @return float|null
*/
public function getTimeout()
{
return $this->timeout;
}
/**
* 获取idle超时时间
* @return float|null
*/
public function getIdleTimeout()
{
return $this->idleTimeout;
}
/**
* 设置超时时间
* @param int|float|null $timeout
* @return self
*/
public function setTimeout($timeout)
{
$this->timeout = $this->validateTimeout($timeout);
return $this;
}
/**
* 设置idle超时时间
* @param int|float|null $timeout
* @return self
*/
public function setIdleTimeout($timeout)
{
if (null !== $timeout && $this->outputDisabled) {
throw new \LogicException('Idle timeout can not be set while the output is disabled.');
}
$this->idleTimeout = $this->validateTimeout($timeout);
return $this;
}
/**
* 设置TTY
* @param bool $tty
* @return self
*/
public function setTty($tty)
{
if ('\\' === DS && $tty) {
throw new \RuntimeException('TTY mode is not supported on Windows platform.');
}
if ($tty && (!file_exists('/dev/tty') || !is_readable('/dev/tty'))) {
throw new \RuntimeException('TTY mode requires /dev/tty to be readable.');
}
$this->tty = (bool) $tty;
return $this;
}
/**
* 检查是否是tty模式
* @return bool
*/
public function isTty()
{
return $this->tty;
}
/**
* 设置pty模式
* @param bool $bool
* @return self
*/
public function setPty($bool)
{
$this->pty = (bool) $bool;
return $this;
}
/**
* 是否是pty模式
* @return bool
*/
public function isPty()
{
return $this->pty;
}
/**
* 获取工作目录
* @return string|null
*/
public function getWorkingDirectory()
{
if (null === $this->cwd) {
return getcwd() ?: null;
}
return $this->cwd;
}
/**
* 设置工作目录
* @param string $cwd
* @return self
*/
public function setWorkingDirectory($cwd)
{
$this->cwd = $cwd;
return $this;
}
/**
* 获取环境变量
* @return array
*/
public function getEnv()
{
return $this->env;
}
/**
* 设置环境变量
* @param array $env
* @return self
*/
public function setEnv(array $env)
{
$env = array_filter($env, function ($value) {
return !is_array($value);
});
$this->env = [];
foreach ($env as $key => $value) {
$this->env[(binary) $key] = (binary) $value;
}
return $this;
}
/**
* 获取输入
* @return null|string
*/
public function getInput()
{
return $this->input;
}
/**
* 设置输入
* @param mixed $input
* @return self
*/
public function setInput($input)
{
if ($this->isRunning()) {
throw new \LogicException('Input can not be set while the process is running.');
}
$this->input = Utils::validateInput(sprintf('%s::%s', __CLASS__, __FUNCTION__), $input);
return $this;
}
/**
* 获取proc_open的选项
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* 设置proc_open的选项
* @param array $options
* @return self
*/
public function setOptions(array $options)
{
$this->options = $options;
return $this;
}
/**
* 是否兼容windows
* @return bool
*/
public function getEnhanceWindowsCompatibility()
{
return $this->enhanceWindowsCompatibility;
}
/**
* 设置是否兼容windows
* @param bool $enhance
* @return self
*/
public function setEnhanceWindowsCompatibility($enhance)
{
$this->enhanceWindowsCompatibility = (bool) $enhance;
return $this;
}
/**
* 返回是否 sigchild 兼容模式激活
* @return bool
*/
public function getEnhanceSigchildCompatibility()
{
return $this->enhanceSigchildCompatibility;
}
/**
* 激活 sigchild 兼容性模式。
* @param bool $enhance
* @return self
*/
public function setEnhanceSigchildCompatibility($enhance)
{
$this->enhanceSigchildCompatibility = (bool) $enhance;
return $this;
}
/**
* 是否超时
*/
public function checkTimeout()
{
if (self::STATUS_STARTED !== $this->status) {
return;
}
if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
$this->stop();
throw new ProcessTimeoutException($this, ProcessTimeoutException::TYPE_GENERAL);
}
if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
$this->stop();
throw new ProcessTimeoutException($this, ProcessTimeoutException::TYPE_IDLE);
}
}
/**
* 是否支持pty
* @return bool
*/
public static function isPtySupported()
{
static $result;
if (null !== $result) {
return $result;
}
if ('\\' === DS) {
return $result = false;
}
$proc = @proc_open('echo 1', [['pty'], ['pty'], ['pty']], $pipes);
if (is_resource($proc)) {
proc_close($proc);
return $result = true;
}
return $result = false;
}
/**
* 创建所需的 proc_open 的描述符
* @return array
*/
private function getDescriptors()
{
if ('\\' === DS) {
$this->processPipes = WindowsPipes::create($this, $this->input);
} else {
$this->processPipes = UnixPipes::create($this, $this->input);
}
$descriptors = $this->processPipes->getDescriptors($this->outputDisabled);
if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
$descriptors = array_merge($descriptors, [['pipe', 'w']]);
$this->commandline = '(' . $this->commandline . ') 3>/dev/null; code=$?; echo $code >&3; exit $code';
}
return $descriptors;
}
/**
* 建立 wait () 使用的回调。
* @param callable|null $callback
* @return callable
*/
protected function buildCallback($callback)
{
$out = self::OUT;
$callback = function ($type, $data) use ($callback, $out) {
if ($out == $type) {
$this->addOutput($data);
} else {
$this->addErrorOutput($data);
}
if (null !== $callback) {
call_user_func($callback, $type, $data);
}
};
return $callback;
}
/**
* 更新状态
* @param bool $blocking
*/
protected function updateStatus($blocking)
{
if (self::STATUS_STARTED !== $this->status) {
return;
}
$this->processInformation = proc_get_status($this->process);
$this->captureExitCode();
$this->readPipes($blocking, '\\' === DS ? !$this->processInformation['running'] : true);
if (!$this->processInformation['running']) {
$this->close();
}
}
/**
* 是否开启 '--enable-sigchild'
* @return bool
*/
protected function isSigchildEnabled()
{
if (null !== self::$sigchild) {
return self::$sigchild;
}
if (!function_exists('phpinfo')) {
return self::$sigchild = false;
}
ob_start();
phpinfo(INFO_GENERAL);
return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
}
/**
* 验证是否超时
* @param int|float|null $timeout
* @return float|null
*/
private function validateTimeout($timeout)
{
$timeout = (float) $timeout;
if (0.0 === $timeout) {
$timeout = null;
} elseif ($timeout < 0) {
throw new \InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
}
return $timeout;
}
/**
* 读取pipes
* @param bool $blocking
* @param bool $close
*/
private function readPipes($blocking, $close)
{
$result = $this->processPipes->readAndWrite($blocking, $close);
$callback = $this->callback;
foreach ($result as $type => $data) {
if (3 == $type) {
$this->fallbackExitcode = (int) $data;
} else {
$callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
}
}
}
/**
* 捕获退出码
*/
private function captureExitCode()
{
if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
$this->exitcode = $this->processInformation['exitcode'];
}
}
/**
* 关闭资源
* @return int 退出码
*/
private function close()
{
$this->processPipes->close();
if (is_resource($this->process)) {
$exitcode = proc_close($this->process);
} else {
$exitcode = -1;
}
$this->exitcode = -1 !== $exitcode ? $exitcode : (null !== $this->exitcode ? $this->exitcode : -1);
$this->status = self::STATUS_TERMINATED;
if (-1 === $this->exitcode && null !== $this->fallbackExitcode) {
$this->exitcode = $this->fallbackExitcode;
} elseif (-1 === $this->exitcode && $this->processInformation['signaled']
&& 0 < $this->processInformation['termsig']
) {
$this->exitcode = 128 + $this->processInformation['termsig'];
}
return $this->exitcode;
}
/**
* 重置数据
*/
private function resetProcessData()
{
$this->starttime = null;
$this->callback = null;
$this->exitcode = null;
$this->fallbackExitcode = null;
$this->processInformation = null;
$this->stdout = null;
$this->stderr = null;
$this->process = null;
$this->latestSignal = null;
$this->status = self::STATUS_READY;
$this->incrementalOutputOffset = 0;
$this->incrementalErrorOutputOffset = 0;
}
/**
* 将一个 POSIX 信号发送到进程中。
* @param int $signal
* @param bool $throwException
* @return bool
*/
private function doSignal($signal, $throwException)
{
if (!$this->isRunning()) {
if ($throwException) {
throw new \LogicException('Can not send signal on a non running process.');
}
return false;
}
if ($this->isSigchildEnabled()) {
if ($throwException) {
throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
}
return false;
}
if (true !== @proc_terminate($this->process, $signal)) {
if ($throwException) {
throw new \RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
}
return false;
}
$this->latestSignal = $signal;
return true;
}
/**
* 确保进程已经开启
* @param string $functionName
*/
private function requireProcessIsStarted($functionName)
{
if (!$this->isStarted()) {
throw new \LogicException(sprintf('Process must be started before calling %s.', $functionName));
}
}
/**
* 确保进程已经终止
* @param string $functionName
*/
private function requireProcessIsTerminated($functionName)
{
if (!$this->isTerminated()) {
throw new \LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
}
}
}