协程 shell_exec 如何捕获标准错误流
今天在GitHub主页看到外国友人提了一个很有意思的issue,他在使用Co\\System::exec()执行了一个不存在的命令时,错误信息会直接打印到屏幕,而不是返回错误信息。
实际上Swoole提供的System::exec()行为上与PHP的shell_exec是完全一致的,我们写一个shell_exec的同步阻塞版本,执行后发现同样拿不到标准错误流输出的内容,会被直接打印到屏幕。
<?php$result = shell_exec('unknown');
var_dump($result);
[email protected]:~/workspace/debug$ php s.phpsh: 1: unknown: not found
NULL
[email protected]:~/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就可以拿到标准错误流输出的内容。
[email protected]:~/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 32512
[email protected]:~/workspace/swoole/examples/coroutine$

以上是 协程 shell_exec 如何捕获标准错误流 的全部内容, 来源链接: utcz.com/a/65332.html

