Search code examples
phpchessproc-open

How do you keep the STDIN pipe open all the time when using proc_open?


I'm using a PHP script on Windows to communicate with a chess engine. I'm establishing the connection as follows:

$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());

I can send commands to the engine like this:

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

And I read the engine output like this:

stream_get_contents($pipes[1]);

The problem is that I cannot read the engine output until I close the stdin pipe like this:

fclose($pipes[0]);

That means that I have to constantly open and close the connection (using proc_open) whenever I want to interact with the engine.

How can I keep the connection open all the time?


Solution

  • I suppose it's because you're using stream_get_contents() function, which - by default - reads the whole stream at once.
    If you use, for example:

    fgets($pipes[1]);
    

    you read until the first EOL.

    Using instead:

    fgetc($pipes[1]);
    

    you read character by character...

    I suppose you could even keep using stream_get_contents(), specifying with the second parameter the number of characters you want to read from the stream...