问题
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.
回答1:
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:
Use pipe() to create two pipes, one for the piped stdin, one for the piped stdout.
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, andexec()
s the new process.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.
来源:https://stackoverflow.com/questions/39693924/c-linux-interact-another-program-stdin-stdout