popen is the right tool for this job. You pass it a command to execute, and it return you receive a C file handle (FILE *
) which represents the pipe from your program to the second one. All data you write with this handle is directed to the second program's standard input.
Note that this is a C file handle, so you'll need to use C I/O functions such as fprintf to write to it. Unfortunately, there is no standard way of converting a C file handle to a C++ output stream.
Here is an example of how you might use popen
, adapted from the example in the GNU libc manual:
FILE *pipe = popen("wireshark -i -k", "w"); // "w" means "write mode"
if (!pipe) {
// execution failed
return;
}
fprintf(pipe, "Some data");
…
// When you're done with the pipe:
pclose(pipe);
You can make sure that the program is started only once by storing the pipe FILE *
in a permanent variable (e.g. an object member variable) that you initialize with NULL
. Then you can easily check if you have already started the second application with pipe != NULL
.