C++ Linux Interact Another Program stdin / stdout

夙愿已清 提交于 2020-01-04 09:38:51

问题


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:

  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.



来源:https://stackoverflow.com/questions/39693924/c-linux-interact-another-program-stdin-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!