在命令仍在运行时从php exec()获取结果?

Kyl*_*yle 4 php exec

当我exec像这样运行PHP时:

$result = exec('command');
Run Code Online (Sandbox Code Playgroud)

此结果将存储在$result.但在我目前的情况下,我的命令可能需要几分钟,并在运行时输出结果.有没有办法在运行时获得输出?我知道该passthru方法会将结果输出为浏览器,但实际上我直接想要它.

Sie*_*tse 5

你应该看一下proc_open

在使输出流无阻塞(with stream_set_blocking)之后,您可以随时从中读取,而不会阻止您的PHP代码.

-Edit-如果你使用

$result = exec('command > /path/to/file &');
Run Code Online (Sandbox Code Playgroud)

它将在后台运行,您可以读取/ path/to/file中的输出


小智 5

也许不是最好的方法(但对我有用):

<?php

$cmd = "ping 127.0.0.1 -c 5"; //example command

$descriptorspec = array(
    0 => array("pipe", "r"), 
    1 => array("pipe", "w"), 
    2 => array("pipe", "a")
);

$pipes = array();

$process = proc_open($cmd, $descriptorspec, $pipes, null, null);

echo "Start process:\n";

$str = "";

if(is_resource($process)) {
    do {
        $curStr = fgets($pipes[1]);  //will wait for a end of line
        echo $curStr;
        $str .= $curStr;

        $arr = proc_get_status($process);

    }while($arr['running']);
}else{
    echo "Unable to start process\n";
}

fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);

echo "\n\n\nDone\n";

echo "Result is:\n----\n".$str."\n----\n";

?>
Run Code Online (Sandbox Code Playgroud)