关于php:协程-shellexec-如何捕获标准错误流

9次阅读

共计 1277 个字符,预计需要花费 4 分钟才能阅读完成。

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

实际上 Swoole 提供的 System::exec() 行为上与 PHPshell_exec是完全一致的,咱们写一个 shell_exec 的同步阻塞版本,执行后发现同样拿不到规范谬误流输入的内容,会被间接打印到屏幕。

<?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\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 个形容信息:

  • fd0 的流是规范输出,能够在主过程外向这个流写入数据,子过程就能够失去数据
  • fd1 的流是规范输入,这里能够失去执行命令的输入内容
  • fd2pipe stream 就是 stderr,读取 stderr 就能拿到错误信息输入

应用 fread 就能够拿到规范谬误流输入的内容。

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-server

正文完
 0