CircuitGuy CircuitGuy - 1 year ago 107
Linux Question

C++ Linux Interact Another Program stdin / stdout

I have an executable in Linux that can interact with stdin/stdout. I'm trying to write a program in C++ that can interactively call this program, send commands to its stdin, and capture it's stdout.

I've been getting really confused. I don't want to fork my program (do I?). I do want my program to be able to start the "client", send data, get output, send more data, get more output, ..., and close the "client".

P.S. Yes, I'm sure this has been asked before, but I've spent a few hours really scratching my head- probably not using the correct keywords.

Answer Source

The only way to execute another program is via one of the exec() system calls. This is the only way. And, as you know, exec() replaces the executing program with the program specified by exec(). The process that issued the exec() will not exist any more, it's PID is now used by the new program.

It therefore logically follows, that unless you want your program to be replaced by that other executable, your program must fork(), and the child process uses exec() to execute the new executable. This is the traditional way to start a new process, and continue running the original process. A fork() is required for that.

The situation you describe is fairly typical, paint-by-the-numbers situation, that's been done countless of times:

  1. Use pipe() to create two pipes, one for the piped stdin, one for the piped stdout.

  2. Use fork(). The child process dup2()s the read end of the stdin pipe to 0, the write end of the stdout pipe to 1, closes both ends of each of the original pipes, and exec()s the new process.

  3. The parent process closes the read end of the stdin pipe, the write end of the stdout pipe, then proceeds to interact with the child process using the write end of the stdin pipe and the read end of the stdout pipe.