在C++中实现Stockfish的子进程运行

nfs0ujit  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(148)

我目前正尝试用C++中的Stockfish国际象棋引擎运行简单的测试,以获得最佳的可能走法。我将Stockfish作为子进程启动,并希望使用输入和输出流来传递所需的UCI命令,我正在通过管道与父进程交换这些命令。然而,当我运行代码时,Stockfish只是启动了,没有发生任何其他事情。然后在CLI中输入UCI命令就可以工作了,但这显然不是目标。我做错了什么?

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

void sig_handler(int sig) {}

int main() {
    int fd1[2];
    if (pipe(fd1) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }    

    int pid = fork();
    if (pid == 0) {
        execl("./stockfish", "./stockfish", nullptr);
        close(fd1[1]);
        char position[60];
        read(fd1[0], position, 60);
        close(fd1[0]);
        cout << "position " << position << endl;
        cout << "go" << endl;
        sleep(5000);
        cout << "stop" << endl;
        string move;
        cin >> move;
        exit(0);
    }

    else {
        close(fd1[0]);
        cout << "Parent process" << endl;
        string line = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
        write(fd1[1], line.c_str(), strlen(line.c_str()) + 1);
        close(fd1[1]);

        signal(SIGINT, &sig_handler);
        wait(NULL);
        cout << "Parent done" << endl;
    }
    return 0;
}
8e2ybdfx

8e2ybdfx1#

多亏了@TedLyngmo和一些关于Boost库的研究,它非常容易实现:

#include <boost/process.hpp>
#include <boost/asio.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

using namespace std;
namespace bp = boost::process;

int main() {
    bp::ipstream is;
    bp::opstream os;

    bp::child c("./stockfish", bp::std_in < os, bp::std_out > is);
    os << "uci" << endl;
    os << "isready" << endl;
    os << "position fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" << endl;
    os << "go depth 30" << endl;

    string line;
    string move_string;
    while (getline(is, line)) {
        if (!line.compare(0, 8, "bestmove")) {
            move_string = line;
            break;
        }
    }
    // Delete the "bestmove" part of the string and get rid of any trailing characters divided by space
    move_string = move_string.substr(9, move_string.size()-9);
    vector<string> mv;
    boost::split(mv, move_string, boost::is_any_of(" "));
    cout << "Stockfish move: " << mv.at(0) << endl;

    return 0;
}

相关问题