proc_open()输出问题

时间:2017-07-24 05:36:23

标签: php proc-open

我有一个小的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();

1 个答案:

答案 0 :(得分:0)

当使用CLI的CLI版本时,输出仍然是缓冲的 - 所以将页面发送给用户的通常时间是在脚本的末尾。

与任何版本的PHP一样 - 使用flush()会强制将输出发送给用户。

此外 - 您应该使用PHP_EOL,它会为您开启的任何平台输出正确的新行(Linux和Windows使用不同的字符 - \ r \ n或\ n)。 PHP_EOL是一种创建新行的安全方式。

相关问题