【发布时间】:2017-07-24 05:36:23
【问题描述】:
我有一个小的 PHP 编写的 CLI 脚本,它作为 Linux 中基于 CLI 的 calc 的前端。该脚本从用户那里获取数学表达式并将它们传递给calc。然后当用户想要退出时,他只需输入stop。在这种情况下,脚本将exit 发送到calc。这个脚本的问题是它只在用户发送stop 时才显示输出。但是我需要输出每个用户的数学表达式。脚本如下:
<?php
define('BUFSIZ', 1024);
define('EXIT_CMD', 'stop');
function printOutput(&$fd) {
while (!feof($fd)) {
echo fgets($fd, BUFSIZ);
}
}
function &getDescriptorSpec()
{
$spec = array(
0 => array("pty"), // stdin
1 => array("pty"), // stdout
2 => array("pty") // stderr
);
return $spec;
}
function readInputLine(&$fd)
{
echo "Enter your input\n";
$line = trim(fgets($fd));
return $line;
}
function sendCmd(&$fd, $cmd)
{
fwrite($fd, "${cmd}\n");
}
function main() {
$spec = getDescriptorSpec();
$process = proc_open("calc", $spec, $pipes);
if (is_resource($process)) {
$procstdin = &$pipes[0];
$procstdout = &$pipes[1];
$fp = fopen('php://stdin', 'r');
while (TRUE) {
$line = readInputLine($fp);
if (0 === strcmp($line, EXIT_CMD)) {
break;
}
sendCmd($procstdin, $line);
}
sendCmd($procstdin, "exit");
fclose($procstdin);
printOutput($procstdout);
fclose($procstdout);
$retval = proc_close($process);
echo "retval = $retval\n";
fclose($fp);
}
}
main();
【问题讨论】:
-
尝试使用
flush(),因为输出很可能被缓冲了。 -
是的,
flush()+ 一些代码修改做到了!你知道我可以在哪里发布现在可以使用的修改后的代码吗?