明天在GitHub
主页看到外国友人提了一个很有意思的issue
,他在应用Co\\System::exec()
执行了一个不存在的命令时,错误信息会间接打印到屏幕,而不是返回错误信息。
实际上Swoole
提供的System::exec()
行为上与PHP
的shell_exec
是完全一致的,咱们写一个shell_exec
的同步阻塞版本,执行后发现同样拿不到规范谬误流输入的内容,会被间接打印到屏幕。
<?php$result = shell_exec('unknown');var_dump($result);
htf@htf-ThinkPad-T470p:~/workspace/debug$ php s.phpsh: 1: unknown: not foundNULLhtf@htf-ThinkPad-T470p:~/workspace/debug$
那么如何解决这个问题呢?答案就是应用proc_open
+hook
实现。
实例代码
Swoole\Runtime::setHookFlags(SWOOLE_HOOK_ALL);Swoole\Coroutine\run(function () { $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"), ); $process = proc_open('unknown', $descriptorspec, $pipes); var_dump($pipes); var_dump(fread($pipes[2], 8192)); $return_value = proc_close($process); echo "command returned $return_value\n";});
应用proc_open
,传入了3
个形容信息:
fd
为0
的流是规范输出,能够在主过程外向这个流写入数据,子过程就能够失去数据fd
为1
的流是规范输入,这里能够失去执行命令的输入内容fd
为2
的pipe stream
就是stderr
,读取stderr
就能拿到错误信息输入
应用fread
就能够拿到规范谬误流输入的内容。
htf@htf-ThinkPad-T470p:~/workspace/swoole/examples/coroutine$ php proc_open.phparray(3) { [0]=> resource(4) of type (stream) [1]=> resource(5) of type (stream) [2]=> resource(6) of type (stream)}string(26) "sh: 1: unknown: not found"command returned 32512htf@htf-ThinkPad-T470p:~/workspace/swoole/examples/coroutine$
Swoole 正在参加 2020 年度 OSC 中国开源我的项目评比,请点击下方链接投出您的一票,投票中转链接:https://www.oschina.net/p/swoole-server