Interact with another program

Hello everyone,

I am in need to write a program that will interact with another program, the project is to analyze chess games using a chess engine. I do not have to write the chess engine.

If I were to do it manually this is what would happen in console

// Start the engine
$ chess-engine

// Engine reports its name
> Hello I am the chess engine

// Tell the engine in which mode to run. At this point it is like
// an FTP client

> uci

// Engine reports some variables
> var1 check
> var2 check

// set up the board
> position startpos moves e2e4
// Run the analysis
> go depth 7

// Engine thinks and returns the following

> bestmove b8c6 ponder b1c3

This last (the "bestmove" line) is what I want to capture, but to get to that I must go through all the above.

I have tried using popen but a second call is like a brand new "console" and I cant continue from where the first popen left:
1
2
3
4
5
6
7
8
9
10
11
char output[100];
FILE *p = popen("chess-engine", "r");
if (p != NULL) {
    while (fgets(output, sizeof (output), p) != NULL) {
        cout << "This is from output " << output;
        p = popen("uci", "r");
        while (fgets(output, sizeof (output), p) != NULL) {
            cout << "This is from sending uci " << output;
        }
    }
}


I believe there must be a way but my inexperience beats me on this one.

Any help please.
That's an interesting problem you have.

I don't know the solution. I'm just bumping the thread.

I do have one idea though (using WinAPI). CreateProcess function accepts (through STARTUPINFO structure) HANDLEs to stdin, stdout and stderr streams that the process will use. If there was a way to create temporary streams and pass their HANDLEs to CreateProcess, you could use them to communicate as if you were using the command line. I don't know how to do that though. Maybe creating a couple of files could work. Although it's a bit ugly.
Crete two half-duplex UNIX pipes with pipe(), fork(), dup2(), exec() -
one for stdout of your program => stdin of engine
and another for stdout of engine => stdin of your program.

A tutorial on setting up a half-duplex pipe for interprocess communication via stdout/stdin:
http://tldp.org/LDP/lpg/node9.html
Thank you both for very useful replies and for your time :) The tutorial posted by JLBorges seems to be exactly what I wanted so double thanks!

As a side note, I found a way to accomplish this task in PHP using proc_open:
http://php.net/proc_open

I will not dwelve into a debate of performance here but Im just saying proc_open does this.

Live long and prosper :)
Why no use client/server sockets? Here the chess engine is the server and your program the client
The UCI protocol requires communication via stdin and stdout.
Topic archived. No new replies allowed.