Heim  >  Artikel  >  Backend-Entwicklung  >  php执行shell脚本,得到标准输出和错误输出

php执行shell脚本,得到标准输出和错误输出

WBOY
WBOYOriginal
2016-09-08 08:29:361525Durchsuche

1.问题

在php代码中需要执行一个shell脚本,希望分别得到它的标准输出(stdout)错误输出(stderr)。用shell的重定向把标准输出和错误输出放到文件中再用php读取文件,可行,但输出文件的内容传回php后就不再需要,有没有办法把shell的输出重定向到变量?

要执行脚本的功能,无法用php本身完成(执行R语言的脚本),并且需要把常规输出和错误输出都反馈。

2.已有尝试

shell里面的重定向可以把标准输出和错误输出分别放到文件中,但产生临时文件。

<code class="bash">my_cmd 1>out.txt 2>err.txt</code>

php再读取out.txterr.txt文件内容进行返回。

这样做的缺点:产生了中间文件。如果shell命令my_cmd执行的时间比较长(可能要几分钟),那么同一用户如果短时间内多次发起http请求使得php执行my_cmd,则需要每次out.txterr.txt的名字都不同,以免写入冲突。这就产生了很多不必要的中间文件。即使及时删除它们,对于I/O还是有开销,希望能避免。

php的exec()函数:

<code>string exec ( string $command [, array &$output [, int &$return_var ]] )</code>

里面的参数$output看起来只能得到“运行脚本时屏幕输出”的内容,是stdout或者stdout和stderr的混合,不能分开获得。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn