2015-05-26 101 views
-4

我正在使用Java作为国际象棋的前端AI我正在写。 Java处理所有图形,然后使用几个命令行参数执行一些C语言。有时C将永远不会完成,并且不会回到Java。我找到了发生这种情况的案例,并用.exe和java来测试它们。当我拿出java时,这些情况每次都有效。我不确定该从哪里出发。下面是一些代码,我认为是初步认识,以及整个项目作为https://github.com/AndyGrant/JChess从Java执行C奇怪的错误

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(); 
} 
+1

无法分辨您发布的内容。不愿意通读该项目。 – duffymo

+0

我在使用java的RunTime执行C程序时正在寻找可能的错误。 – AndrewGrant

+0

如果“C永远不会完成”,你能证明你的C代码不会陷入某个无限循环吗?如果你在C程序返回的'main'函数之前放置'print'语句,是否打印?仅仅因为你手动给C程序提供了正确的输入并且它终止了并不意味着C程序应该在与Java程序集成时终止。例如,您的Java程序可能会错误地格式化输入。我不会马上说,你在使用Runtime时会出现一些奇怪的错误。 – user2570465

回答

2

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

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

尝试移动你的engine.waitFor()之后的部分,你阅读它的所有输入。

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

+0

这是正确的答案,对于迟到的回复感到抱歉。 – AndrewGrant

0

也许去除

while (true){ 

} 

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

+0

我在该无限循环之前有一个打印语句表示问题。 – AndrewGrant