协程 shell_exec 如何捕获标准错误流

今天在GitHub主页看到外国友人提了一个颇有意思的issue,他在使用Co\System::exec()执行了一个不存在的命令时,错误信息会直接打印到屏幕,而不是返回错误信息。php

实际上Swoole提供的System::exec()行为上与PHPshell_exec是彻底一致的,咱们写一个shell_exec的同步阻塞版本,执行后发现一样拿不到标准错误流输出的内容,会被直接打印到屏幕。shell

<?php
$result = shell_exec('unknown');
var_dump($result);
htf@htf-ThinkPad-T470p:~/workspace/debug$ php s.php
sh: 1: unknown: not found
NULL
htf@htf-ThinkPad-T470p:~/workspace/debug$

那么如何解决这个问题呢?答案就是使用proc_open+hook实现。swoole

实例代码

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个描述信息:spa

  • fd0 的流是标准输入,能够在主进程内向这个流写入数据,子进程就能够获得数据
  • fd1 的流是标准输出,这里能够获得执行命令的输出内容
  • fd2pipe stream 就是 stderr ,读取 stderr 就能拿到错误信息输出

使用fread就能够拿到标准错误流输出的内容。.net

htf@htf-ThinkPad-T470p:~/workspace/swoole/examples/coroutine$ php proc_open.php
array(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
htf@htf-ThinkPad-T470p:~/workspace/swoole/examples/coroutine$

Swoole 正在参与 2020 年度 OSC 中国开源项目评选,请点击下方连接投出您的一票,投票直达连接:https://www.oschina.net/p/swoole-serverdebug

Swoole官方