我正在尝试编写一个程序,通过命令行与Stockfish国际象棋引擎交互。我已经研究了使用管道和重定向cin/cout的方法,但问题在于Stockfish运行其自己的shell而不是只输出单行结果,例如:
我试了下面的代码(来自这里)以执行命令并读取它们的输出,但当我尝试运行Stockfish并打印输出时,它从未结束:
~$ stockfish
Stockfish 261014 64 by Tord Romstad, Marco Costalba and Joona Kiiski
> go movetime 5000
[output]
...
> quit
~$
我试了下面的代码(来自这里)以执行命令并读取它们的输出,但当我尝试运行Stockfish并打印输出时,它从未结束:
#include <string>
#include <iostream>
#include <stdio.h>
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
int main(void)
{
std::cout << exec("ls") << std::endl; // this works fine
std::cout << exec("stockfish") << std::endl; // this never ends
return 0;
}
我想问的是,为什么这个方法不起作用,以及如何编写一个程序来发送和接收Stockfish shell中的文本?