使用c++与Stockfish shell接口
Interfacing with Stockfish shell using C++
我正试图通过命令行编写与Stockfish国际象棋引擎接口的程序。我已经研究过使用管道和重定向cin/cout,但问题是Stockfish运行自己的shell,而不仅仅是给出单行输出,例如:
~$ 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发送和接收文本?
while循环只有在检测到管道上的EOF时才会结束,直到打开的命令终止才会结束。等待输入的事实基本上是无法检测到的。
由于popen
只重定向了标准输出,因此打开的stockfish与您的程序共享标准输出。当你开始stockfish时,它会尝试读取输入。如果你不输入什么,什么也不会发生。
所以你应该尝试向stockfish发送你想让它执行的命令,以"quit"命令结束。
Popen只允许您发送或接收数据,具体取决于模式操作数。两者不可兼得。你可以用通常的fork
和exec
技术,或者你可以打开像stockfish < sfcmds.txt
这样的东西。
相关文章:
- 如何通过cpp程序运行shell脚本
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- Visual C++GC接口如何启用它以及要包含哪个库
- shell排序中的交换和比较
- Windows.h与GLFW.h的接口
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 提供与TMP和SFINAE的通用接口
- 为重写std::exception的库生成swig接口时出错
- 内联如何影响模块接口中的成员函数
- COM 接口 c# 封送数组数组
- 如何在 SCIP C++ 接口中获取 MILP 约束矩阵中的系数值
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 如何绑定 C++ gRPC 客户端的网络接口
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 如何从实现接口的模板化类实例访问结构
- 我适合在我的构建系统中使用 shell 脚本而不是AX_CHECK_COMPILE_FLAG吗?
- 带有进度表的 curl 多接口程序
- 设计帮助 - 为不同类型的消息处理通用接口的设计模式
- 使用c++与Stockfish shell接口