gpt4 book ai didi

c++ - 使用 C++ 与 Stockfish shell 交互

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:16:54 24 4
gpt4 key购买 nike

我正在尝试编写一个通过命令行与 Stockfish 国际象棋引擎交互的程序。我研究过使用管道和重定向 cin/cout,但问题是 Stockfish 运行它自己的 shell 而不是只给出单行输出,例如:

~$ stockfish 
Stockfish 261014 64 by Tord Romstad, Marco Costalba and Joona Kiiski
> go movetime 5000
[output]
...
> quit
~$

我尝试了以下代码(来自 here)来读取执行命令并读回它们,但是当我尝试运行 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 发送和接收文本的程序?

最佳答案

您的 while 循环只会在检测到管道上的 EOF 时结束,并且直到 popen'd 命令终止时才会结束。它正在等待输入的事实基本上是检测不到的。

popen只重定向了 stdout,popen'd stockfish 与您的程序共享 stdin。当您启动 stockfish 时,它会尝试读取输入。如果您不输入任何内容,则什么也不会发生。

因此,您应该尝试向 stockfish 发送您希望它执行的命令,并以“退出”命令结束。

Popen 仅允许您发送 接收数据,具体取决于模式操作数。你永远不能两者兼得。你可以照常做 forkexec技术,或者你可以打开类似 stockfish < sfcmds.txt 的东西.

关于c++ - 使用 C++ 与 Stockfish shell 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32301415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com