使用proc_open时如何保持STDIN管道一直打开?

时间:2015-01-12 13:36:20

标签: php chess proc-open

我在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]);

问题是我在关闭stdin管道之前无法读取引擎输出:

fclose($pipes[0]);

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

如何保持连接始终打开?

1 个答案:

答案 0 :(得分:1)

我想这是因为您使用的是stream_get_contents()函数,默认情况下会立即读取整个流。
如果您使用,例如:

fgets($pipes[1]);

你读到第一个EOL。

改为使用:

fgetc($pipes[1]);

你逐字逐句地阅读...

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

相关问题