Xiecheng shell_ How to capture standard error stream in Exec

Time:2021-4-18

Today inGitHubI saw a very interesting question from foreign friends on the homepageissueHe’s using itCo\System::exec()When a non-existent command is executed, the error message will be printed directly to the screen instead of returning the error message.

actuallySwooleProvidedSystem::exec()Behavior andPHPOfshell_execIt’s exactly the same. Let’s write oneshell_execAfter execution, it is found that the output of standard error stream is not available, and it will be printed directly to the screen.

<?php
$result = shell_exec('unknown');
var_dump($result);
[email protected]:~/workspace/debug$ php s.php
sh: 1: unknown: not found
NULL
[email protected]:~/workspace/debug$

So how to solve this problem? The answer is to useproc_open+hookrealization.

Instance code

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";
});

useproc_open, introduced3Description information:

  • fdby0The stream of is the standard input. You can write data to the stream in the main process, and the child process can get the data
  • fdby1The stream of is the standard output, where you can get the output content of executing the command
  • fdby2Ofpipe streamnamelystderr, readstderrYou can get the error message output

usefreadYou can get the output of the standard error stream.

[email protected]:~/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
[email protected]:~/workspace/swoole/examples/coroutine$

Swoole is participating in the 2020 OSC China open source project selection. Please click the link below to cast your vote. The direct voting link is as follows:https://www.oschina.net/p/swoole-server

Xiecheng shell_ How to capture standard error stream in Exec

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]