PHP:需要关闭STDIN才能读取STDOUT


PHP: Need to close STDIN in order to read STDOUT?

我最近尝试使用PHP函数proc_open与我的Ubuntu web服务器[1]上的二进制文件进行通信。我可以建立连接并定义管道STDIN、STDOUT和STDERR。好。

现在我正在谈论的二进制是一个交互式计算机代数软件-因此我希望在第一个命令之后保持STDOUT和STDIN存活,这样我仍然可以在几行之后以交互式方式使用该应用程序(从web前端直接用户输入)。

然而,事实证明,用于读取二进制文件(stream_get_contents或fgets)的STDOUT的PHP函数需要一个封闭的STDIN才能工作。否则程序会死锁。

这是一个严重的缺点,因为我不能在关闭STDIN后重新打开它。所以我的问题是:为什么我的脚本死锁,如果我想读取STDOUT时,我的STDIN还活着?

谢谢Jens

[1] proc_open返回false但没有写入错误文件-权限问题?

我的来源:

$descriptorspec = array(
    0 => array("pipe","r"),
    1 => array("pipe","w"),
    2 => array("file","./error.log","a")
) ;
// define current working directory where files would be stored
$cwd = './' ;
// open reduce
$process = proc_open('./reduce/reduce', $descriptorspec, $pipes, $cwd) ;
if (is_resource($process)) {
    // some valid Reduce commands
    fwrite($pipes[0], 'load excalc; operator x; x(0) := t; x(1) := r;');
    // if the following line is removed, the script deadlocks
    fclose($pipes[0]);
    echo "output: " . stream_get_contents($pipes[1]);
    // close pipes & close process
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);
}
编辑:

这段代码可以工作。某种程度上是因为它使用usslept来等待非阻塞的STDOUT被数据填充。我怎么才能做得更优雅呢?

@ Elias:通过轮询$status['running']条目,您只能确定整个进程是否仍在运行,但不能确定进程是否繁忙或空闲…这就是为什么我必须包含这些ussleep。

define('TIMEOUT_IN_MS', '100');
define('TIMEOUT_STEPS', '100');
function getOutput ($pipes) {
    $result = "";
    $stage = 0;
    $buffer = 0;
    do {
        $char = fgets($pipes[1], 4096);
        if ($char != null) {
            $buffer = 0;
            $stage = 1;
            $result .= $char;
        } else if ($stage == "1") {
            usleep(TIMEOUT_IN_MS/TIMEOUT_STEPS);
            $buffer++;
            if ($buffer > TIMEOUT_STEPS) {
                $stage++;
            }
        }
    } while ($stage < 2);
    return $result;
}
$descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w") ) ;
// define current working directory where files would be stored
$cwd = './' ;
// open reduce
$process = proc_open('./reduce/reduce', $descriptorspec, $pipes, $cwd);
if (is_resource($process)) {
    stream_set_blocking($pipes[1], 0);
    echo "startup output:<br><pre>" . getOutput($pipes) . "</pre>";
    fwrite($pipes[0], 'on output; load excalc; operator x; x(0) := t; x(1) := r;' . PHP_EOL);
    echo "output 1:<br><pre>" . getOutput($pipes) . "</pre>";
    fwrite($pipes[0], 'coframe o(t) = sqrt(1-2m/r) * d t, o(r) = 1/sqrt(1-2m/r) * d r with metric g = -o(t)*o(t) + o(r)*o(r); displayframe;' . PHP_EOL);
    echo "output 2:<br><pre>" . getOutput($pipes) . "</pre>";
    // close pipes & close process
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);
}

这让我想起了我之前写的一个脚本。虽然它可能会给你(或其他人)带来灵感,但它并不能满足你的需要。它所做的包含的是一个示例,说明如何在不关闭任何流的情况下读取流的输出。也许你可以把同样的逻辑应用到你的情况中:

$allInput = array(
    'load excalc; operator x; x(0) := t; x(1) := r;'
);//array with strings to pass to proc
if (is_resource($process))
{
    $output = '';
    $input = array_shift($allInput);
    do
    {
        usleep(200);//make sure the running process is ready
        fwrite(
            $pipes,
            $input.PHP_EOL,//add EOL
            strlen($input)+1
        );
        fflush($pipes[0]);//flush buffered data, write to stream
        usleep(200);
        $status = proc_get_status($process);
        while($out = fread($pipes[1], 1024) && !feof($pipes[1])) 
            $output .= $out;
    } while($status['running'] && $input = array_shift($allInput));
    //proc_close & fclose calls here
}

现在,看到我不知道它到底是你想做什么,这段代码将需要调整相当多。例如,您可能发现自己不得不将STDIN和STDOUT管道设置为非阻塞。
在调用proc_open之后添加这个很简单:

 stream_set_blocking($pipes[0], 0);
 stream_set_blocking($pipes[1], 0);

玩,玩得开心,也许让我知道这个答案在任何方面有帮助…

我猜您做的一切都是正确的,除了二进制文件从未通知它已接收到所有输入并可以开始工作。通过关闭STDIN,您将开始工作流程,因为很明显将不再有更多的输入。如果您没有关闭STDIN,则二进制文件正在等待更多的输入,而您的端正在等待它的输出。

您可能需要用换行符或您期望的任何其他协议操作来结束输入。或者关闭STDIN是您期望的操作。除非专门为保持开放并继续流输入而创建流程,否则您无法让它这样做。如果进程读取所有输入,处理它,返回输出,然后退出,那么您就无法使它保持活动状态,以便以后处理更多的输入。如果流程显式地支持该行为,则应该有一个关于如何划分输入的定义。