I am currently trying to run simple tests with the Stockfish chess engine in C++ to get the best possible move. I am starting Stockfish as a child process and want to use the input and output streams to pass on the desired UCI commands, which I am exchanging with the parent process via a pipe. However, when I run the code, Stockfish just starts and nothing else happens. Typing in the UCI commands in the CLI then works, but that's obviously not the goal. What am I doing wrong?
#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;
}