Exec() 之后的 PHP StdErr

标签 php exec stderr

在 PHP 中,我使用 exec() 执行一个命令,如果成功则返回一个 URL;

$url = exec('report');

但是,如果出现问题,我想检查 stderr。我将如何阅读流? 我想使用 php://stderr,但我不确定如何使用它。

最佳答案

如果你想执行一个命令,同时得到 stderrstdout,而不是“合并”,一个解决方案可能会使用 proc_open ,它提供了对正在执行的命令的高度控制——包括一种管道 stdin/stdout/stderr 的方法。

这里是一个例子:假设我们有这个 shell 脚本,在 test.sh 中,它写入 stderrstdout :

#!/bin/bash

echo 'this is on stdout';
echo 'this is on stdout too';

echo 'this is on stderr' >&2;
echo 'this is on stderr too' >&2;

现在,让我们在 temp.php 中编写一些 PHP 代码——首先,我们初始化 i/o 描述符:

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin
   1 => array("pipe", "w"),  // stdout
   2 => array("pipe", "w"),  // stderr
);

然后,使用这些描述符在当前目录中执行 test.sh 命令,并说 i/o 应该来自/到 $pipes :

$process = proc_open('./test.sh', $descriptorspec, $pipes, dirname(__FILE__), null);

我们现在可以从两个输出管道中读取:

$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);

$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);

而且,如果我们输出这两个变量的内容:

echo "stdout : \n";
var_dump($stdout);

echo "stderr :\n";
var_dump($stderr);

我们在执行 temp.php 脚本时得到以下输出:

$ php ./temp.php
stdout :
string(40) "this is on stdout
this is on stdout too
"
stderr :
string(40) "this is on stderr
this is on stderr too
"

关于Exec() 之后的 PHP StdErr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2320608/

相关文章:

php - Soundcloud (Oauth2) API 获取访问 token 失败

php - 这是什么格式?

php - 在 PHP 中执行 shell 命令而不等待结果

python - redirect_stderr 不起作用(Python 3.5)

c - 当 POSIX 说 stderr 应该可以读写时是什么意思?

php - 需要检查用户在我的网站 Laravel 5.2 上注册了多长时间

php - 使用 dsql 创建数据库查询

c - 拆分 Unix 命令以与 exec 一起使用

c++ - 使用 execv 执行基本 I/O

C: perror, stdout 输出顺序