2011-05-08 21 views
2

我正在控制我的程序中的Gnuplot進行擬合和繪圖;然而,要獲得合適的參數回來,我想使用的Gnuplot的打印功能:C++控制同時另一個程序的I/O

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); 

我已經讀了很多關於popen()fork()等等,但在這裏還是在其他網站上提供的答案要麼缺乏徹底的解釋,與我的問題無關,或者太難理解(我剛剛開始編程)。

供參考:我使用Linux,g ++和通常的gnome終端。

回答

4

我發現這個準備使用的答案:Can popen() make bidirectional pipes like pipe() + fork()?

pfunc你提供,你要dup2收到的參數stdinstdout,然後exec gnuplot的文件描述符,例如:

#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 

我省略了錯誤檢查。

+2

+1爲好的x-ref。 – 2011-05-08 14:38:26

+0

我是否在管道流中使用這些重複項,或者是否應該在我的原始管道中執行該功能以便自動切換?我很抱歉,但正如我所說,我只是一個初學者。 – Marv 2011-05-08 20:45:28

+1

被欺騙的文件描述符在孩子中被創建和使用。 Duping安排的東西,所以當gnuplot從標準描述符讀寫時,它實際上是通過兩個管道與父進程通信的。在內部,單向'popen'也使用dup2重定向單個文件描述符。 – 2011-05-08 21:08:42

相關問題