【发布时间】:2014-07-18 13:45:16
【问题描述】:
我最近尝试使用 PHP 函数 proc_open 与我的 Ubuntu 网络服务器 [1] 上的二进制文件进行通信。我可以建立连接并定义管道 STDIN、STDOUT 和 STDERR。不错。
现在我正在与之交谈的二进制文件是一个交互式计算机代数软件 - 因此我希望在第一个命令之后保持 STDOUT 和 STDIN 处于活动状态,这样我仍然可以在几行之后以交互方式使用该应用程序(直接来自网络前端的用户输入)。
然而,事实证明,读取二进制文件的 STDOUT(stream_get_contents 或 fgets)的 PHP 函数需要一个封闭的 STDIN 才能工作。否则程序死锁。
这是一个严重的缺点,因为我不能在关闭后重新打开已关闭的 STDIN。所以我的问题是:如果我想在我的 STDIN 还活着的情况下读取 STDOUT,为什么我的脚本会死锁?
谢谢 延斯
[1]proc_open returns false but does not write in error file - permissions issue?
我的来源:
$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);
}
编辑:
这种代码很有效。有点因为它使用 usleeps 来等待非阻塞的 STDOUT 被数据填充。我该如何更优雅地做到这一点?
@ Elias:通过轮询 $status['running'] 条目,您只能确定整个进程是否仍在运行,但不能确定进程是忙还是空闲...这就是为什么我必须包括这些 usleeps .
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);
}
【问题讨论】:
-
我不确定我是否可以遵循:条目 $pipes[0] 是连接到我的二进制文件的 STDIN 的流的句柄。我可以模拟所有类型的输入以及我得到的工作。但是在读取 $pipes[1] 之前,我必须关闭 $pipes[0]。我不能只从文件中加载内容,因为会话必须是交互式的,所以这不是一个选项。
-
忽略这个,我有个想法,不知道行不行,但是写评论太多了,我把它作为答案发布