Created
October 11, 2023 01:40
-
-
Save jstaursky/6e871762ff6e9c580a8eda46da8be946 to your computer and use it in GitHub Desktop.
linux pipes example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <cstdio> | |
#include <string> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <sys/wait.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
/* | |
This illustrates how to communicate with an external application by sending text to stockfish and receiving text from stockfish. | |
*/ | |
#define READ 0 | |
#define WRITE 1 | |
int main(int argc, char *argv[]) | |
{ | |
int pipe_to_stockfish[2]; | |
int pipe_from_stockfish[2]; | |
if ((pipe2 (pipe_to_stockfish, O_NONBLOCK) < 0) || (pipe2 (pipe_from_stockfish, O_NONBLOCK) < 0)) | |
{ | |
perror ("pipe failure"); | |
exit (EXIT_FAILURE); | |
} | |
auto pid = fork(); | |
if (pid == 0) { | |
/* Child process */ | |
// Close unused ends of pipes | |
close (pipe_to_stockfish[WRITE]); | |
close (pipe_from_stockfish[READ]); | |
// Redirect standard input and output to the pipes | |
dup2 (pipe_to_stockfish[READ], STDIN_FILENO); | |
dup2 (pipe_from_stockfish[WRITE], STDOUT_FILENO); | |
// Close the duplicate file descriptors | |
close (pipe_to_stockfish[READ]); | |
close (pipe_from_stockfish[WRITE]); | |
execlp("/usr/games/stockfish", "/usr/games/stockfish", NULL); | |
exit(0); | |
} | |
else { | |
/* Parent process */ | |
close (pipe_to_stockfish[READ]); | |
close (pipe_from_stockfish[WRITE]); | |
std::string s = "uci\n"; | |
auto nbytes = write(pipe_to_stockfish[WRITE], s.c_str(), s.size()); | |
sleep(1); | |
std::stringstream ss; | |
ssize_t r; | |
do { | |
char buf[80] = {0}; | |
r = read(pipe_from_stockfish[READ], buf, sizeof(buf)- 1); | |
if (r > 0) | |
ss << buf; | |
} while ((r != 0)); | |
std::cout << "parent process received " << r << " bytes" << std::endl; | |
std::cout << ss.str(); | |
} | |
wait(NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment