【问题标题】:How do you keep the STDIN pipe open all the time when using proc_open?使用 proc_open 时如何保持 STDIN 管道始终打开?
【发布时间】:2015-01-12 13:36:20
【问题描述】:

我在 Windows 上使用 PHP 脚本与国际象棋引擎进行通信。 我建立连接如下:

$descriptorspec = array(
                0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
                1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
                2 => array("file","./error.log","a")
        );
$resource = proc_open("stockfish.exe", $descriptorspec, $pipes, null, array());

我可以像这样向引擎发送命令:

fwrite($pipes[0], "uci" . PHP_EOL);

我这样读取引擎输出:

stream_get_contents($pipes[1]);

问题是我无法读取引擎输出,直到我像这样关闭标准输入管道:

fclose($pipes[0]);

这意味着每当我想与引擎交互时,我必须不断地打开和关闭连接(使用 proc_open)。

如何保持连接一直打开?

【问题讨论】:

    标签: php chess proc-open


    【解决方案1】:

    我想这是因为您正在使用 stream_get_contents() 函数,默认情况下,它会一次读取整个流。
    如果你使用,例如:

    fgets($pipes[1]);
    

    您一直阅读到第一个 EOL。

    改用:

    fgetc($pipes[1]);
    

    你一个字一个字地读...

    我想你甚至可以继续使用stream_get_contents(),用第二个参数指定你想从流中读取的字符数......

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 2018-02-22
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多