C++ control I/O of another program simultaneously
I'm controlling Gnuplot within my program for fitting and plotting; however, to get the fit parameters back, I want to use Gnuplot's print-function:
开发者_开发技巧FILE *pipe = popen("gnuplot -persist", "w");
fprintf(pipe, "v(x) = va_1*x+vb_1\n");
fprintf(pipe, "fit v(x) './file' u 1:2 via va_1,vb_1 \n")
fprintf(pipe, "print va_1"); // outputs only the variable's value as a string to
// a new line in terminal, this is what I want to get
...
pclose(pipe);
I've read a lot about popen()
, fork()
and so on but the answers presented here or on other sites were either lacking a thorough explanation, not related to my problem or simply too hard to understand (I'm just beginning to program).
FYI: I'm using Linux, g++ and the usual gnome-terminal.
I found this ready-to-use answer: Can popen() make bidirectional pipes like pipe() + fork()?
In the pfunc
you supply, you have to dup2
the file descriptors received as arguments to stdin
an stdout
and then exec
gnuplot, for example:
#include <unistd.h>
void gnuplotProcess (int rfd, int wfd)
{
dup2( STDIN_FILENO, rfd );
dup2( STDOUT_FILENO, wfd );
execl( "gnuplot", "gnuplot", "-persist" );
}
int fds[2];
pid_t gnuplotPid = pcreate(fds, gnuplotProcess);
// now, talk with gnuplot via the fds
I omitted any error checking.
精彩评论