2

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Marv
  • 55
  • 1
  • 3

1 Answers1

4

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.

Community
  • 1
  • 1
Peter G.
  • 14,786
  • 7
  • 57
  • 75
  • Do I acccess those duplicates within pipe-streams or is that function supposed to be executed within my original pipe so as to automatically switch in between? I'm sorry, but as I said, I'm only a beginner. – Marv May 08 '11 at 20:45
  • 1
    The duped file descriptors are created and used in the child. Duping arranges things so when gnuplot reads and writes from standard descriptors it actually communicates with the parent process by the two pipes. Internally, the unidirectional `popen` also uses dup2 to redirect a single file descriptor. – Peter G. May 08 '11 at 21:08