【问题标题】:C++ control I/O of another program simultaneouslyC++同时控制另一个程序的I/O
【发布时间】:2011-08-21 03:23:49
【问题描述】:

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

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() 等的内容,但这里或其他网站上提供的答案要么缺乏详尽的解释,要么与我的问题无关,要么就是太难以理解(I' m 刚开始编程)。

仅供参考:我使用的是 Linux、g++ 和常用的 gnome 终端。

【问题讨论】:

    标签: c++ linux input pipe


    【解决方案1】:

    我找到了这个现成的答案:Can popen() make bidirectional pipes like pipe() + fork()?

    在您提供的pfunc 中,您必须将文件描述符作为stdinstdout 的参数接收到dup2,然后是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
    

    我省略了任何错误检查。

    【讨论】:

    • 我是在管道流中访问这些重复项,还是应该在我的原始管道中执行该功能以便在两者之间自动切换?对不起,但正如我所说,我只是一个初学者。
    • 复制的文件描述符在子进程中创建和使用。 Duping 安排了事情,所以当 gnuplot 从标准描述符读取和写入时,它实际上通过两个管道与父进程通信。在内部,单向popen 也使用 dup2 来重定向单个文件描述符。
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2023-03-17
    相关资源
    最近更新 更多