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

明天在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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理