从 Java 个奇怪的错误中执行 C

executing C from Java strange errors

我正在使用 Java 作为我正在编写的国际象棋 AI 的前端。 Java 处理所有图形,然后使用一些命令行参数执行一些 C。有时C永远也写不完,回不去Java。我发现了发生这种情况的案例,并仅使用 .exe 而没有 java 对其进行了测试。当我取出 java 时,这些案例每次都有效。我不知道从这里去哪里。这是一些我认为相关的代码,整个项目在 https://github.com/AndyGrant/JChess

try{
    Process engine = Runtime.getRuntime().exec(buildCommandLineExecuteString(lastMove));
    engine.waitFor();
    int AImoveIndex = engine.exitValue();

    String line;
    BufferedReader input = new BufferedReader(new InputStreamReader(engine.getInputStream()));
    while ((line = input.readLine()) != null) 
        System.out.println(line);
    input.close();

    if (AImoveIndex == -1){
        activeGame = false;
        System.out.println("Fatal Error");
        while (true){

        }
    }

    else{
        JMove AIMove = JChessEngine.getAllValid(types,colors,moved,lastMove,!gameTurn).get(AImoveIndex);
        AIMove.makeMove(types,colors,moved);
        lastMove = AIMove;
        validMoves = JChessEngine.getAllValid(types,colors,moved,lastMove,gameTurn);
    }

    waitingOnComputer = false;
    parent.repaint();
}   

catch(Exception e){
    e.printStackTrace();
}

也许删除

while (true){

}

如果你的AImoveIndex == -1,你的程序将进入一个永无止境的循环。

有时,外部进程会卡在 IO 上,试图写入控制台。如果控制台缓冲区已满,下一个 printf 将阻塞。

它向控制台写入了多少文本?

尝试将 engine.waitFor() 移到您从中读取所有输入的部分之后。

另一种方法是让外部进程写入临时文件,然后您读取该临时文件。