C++ program interacting with chess engine doesn't output without Sleep(8000)

75 Views Asked by At

I'm developing a C++ application that writes commands to a chess engine (Stockfish) and reads its output. Strangely, the program fails to display the engine's analysis unless I include a Sleep(8000) function call. Even more curious is that the expected output is displayed if I add Sleep(8000) and comment out the loops that read the engine's output.

Here is a simplified version of my code:

#include <cstdio>
#include <iostream>
#include <string>
#include <Windows.h>

int main() {
    // Open engine process
    FILE* engine = _popen("D:\\testEngine\\stockfish\\stockfish-windows-x86-64-avx2.exe", "w");
    
    if (!engine) {
        std::cerr << "Failed to open engine." << std::endl;
        return 1;
    }

    std::cout << "Enter uci command now" << std::endl;
    // Write UCI command to initialize the engine
    fprintf(engine, "uci\n");
    fflush(engine);

    // Read and print engine initialization information
    char buffer[1024];
    
    while (fgets(buffer, sizeof(buffer), engine)) {
        std::cout << buffer << std::flush;
        if (strstr(buffer, "uciok")) break; // Wait for the engine to send "uciok"
    }
    
    // Send command to analyze
    fprintf(engine, "go movetime 2000\n");
    fflush(engine);

    // Read engine's analysis result
    while (fgets(buffer, sizeof(buffer), engine) != NULL) {
        std::cout << buffer << std::flush;
        if (strstr(buffer, "bestmove")) {
            // When "bestmove" is seen, the engine has completed the analysis
            break;
        }
    }

    Sleep(8000); // This line ensures proper output, reason to be analyzed
    // Close engine process
    _pclose(engine);

    return 0;
}

Without the Sleep(8000) line, there is no output from the engine. With Sleep(8000), the output appears even without the reading loops. Why does Sleep(8000) enable the program to output the analysis details, and how can I ensure the engine's output is captured and displayed correctly without using a fixed sleep duration?

0

There are 0 best solutions below