【问题标题】:how to get output of proc_open()如何获得 proc_open() 的输出
【发布时间】:2011-05-16 08:34:07
【问题描述】:

我尝试从 php 中的proc_open 方法获取输出,但是,当我打印它时,我得到了空。

$descriptorspec = 数组( 0 => 数组(“管道”,“r”), 1 => 数组(“管道”,“w”), 2 => 数组(“文件”、“文件/临时/错误输出.txt”、“a”) ); $process = proc_open("time ./a a.out", $descriptorspec, $pipes, $cwd);

只要我知道,我可以用stream_get_contents()得到输出

echo stream_get_contents($pipes[1]); fclose($pipes[1]);

但我不能这样做.. 有什么建议吗?

感谢之前...

【问题讨论】:

  • 哈哈,你的代码其实让我明白了 proc_open 的工作原理。
  • @Yoshiyahu 哈哈,很高兴知道这一点.. :)

标签: php linux proc-open


【解决方案1】:

这是proc_open() 的另一个示例。 我在这个例子中使用 Win32 ping.exe 命令。 CMIIW

set_time_limit(1800);
ob_implicit_flush(true);

$exe_command = 'C:\\Windows\\System32\\ping.exe -t google.com';

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

$process = proc_open($exe_command, $descriptorspec, $pipes);

if (is_resource($process))
{

    while( ! feof($pipes[1]))
    {
        $return_message = fgets($pipes[1], 1024);
        if (strlen($return_message) == 0) break;

        echo $return_message.'<br />';
        ob_flush();
        flush();
    }
}

希望这会有所帮助 =)

【讨论】:

  • 这里面为什么需要ob_flush和flush?
  • 总结一下:“flush() 可能无法覆盖 Web 服务器的缓冲方案,它对浏览器中的任何客户端缓冲都没有影响。它也不会影响 PHP 的用户空间输出缓冲机制。这意味着你必须同时调用 ob_flush() 和 flush() 来刷新 ob 输出缓冲区,如果你正在使用它们。" 来源:php.net/manual/en/function.flush.php
【解决方案2】:

您的代码或多或少对我有用。 time 将其输出打印到stderr,因此如果您正在寻找该输出,请查看您的文件files/temp/error-output.txtstdout 管道 $pipes[1] 将只包含程序 ./a 的输出。

我的复制人:

[edan@edan tmp]$ cat proc.php 

<?php

$cwd='/tmp';
$descriptorspec = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("file", "/tmp/error-output.txt", "a") );

$process = proc_open("time ./a a.out", $descriptorspec, $pipes, $cwd);

echo stream_get_contents($pipes[1]);
fclose($pipes[1]);

?>

[edan@edan tmp]$ php proc.php 

a.out here.

[edan@edan tmp]$ cat /tmp/error-output.txt

real    0m0.001s
user    0m0.000s
sys     0m0.002s

【讨论】:

  • 感谢您的帮助...我不检查我的标准错误...最后,我检查了它,并找到了输出...谢谢..
猜你喜欢
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 2021-12-15
  • 2019-03-09
  • 1970-01-01
  • 2011-05-16
相关资源
最近更新 更多