This question already has an answer here:
- C++ proc_open analogue 2 answers
I'm struggling in writing a c++ code that would pass some "string" to an external program and get the feedback.
say for example I want to pass a c++ code to gcc and get the error messages back to my original code
how to write that in c++
There are two ways of doing it. The simple way, if you just want to read the output from an external program, is to use
popen
:The other more complicated way (and how
popen
works behind the scenes) is to create a new anonymous pipe (withpipe
), a new process (withfork
), set up the standard output of the new process to use the pipe, and thenexec
the program in the child process. Then you can read the output from the program from the read-end of the pipe. This is more flexible, and the recommended way (even though it's more complicated to set up). It's also the only way if you want to be able to do two-way communication, i.e. write to the external programs standard input and read from its output.