C++同时控制另一个程序的 I/O

C++ control I/O of another program simultaneously

本文关键字:程序 另一个 控制 C++      更新时间:2023-10-16

我正在程序中控制 Gnuplot 以进行拟合和绘图;但是,为了恢复拟合参数,我想使用 Gnuplot 的打印函数:

FILE *pipe = popen("gnuplot -persist", "w");
fprintf(pipe, "v(x) = va_1*x+vb_1n");
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 ++和通常的侏儒终端。

我找到了这个现成的答案:popen() 可以制作像 pipe() + fork() 这样的双向管道吗?

在你提供的pfunc中,你必须dup2作为参数收到的文件描述符,以stdin stdout,然后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

我省略了任何错误检查。