How to pass multiple commands using popen in C?

2019-07-21 21:33发布

I am trying to plot graphs using GNUPLOT which is a command line interface. But I need to integrate it in c program, so that if program gets executed, graph is plotted. This can be done by using popen command. I have made a code where I am doing popen("gnuplot","r") so now when I execute the program, gnuplot starts. But I need to send multiple commands like popen("sin(x)","r") after popen("gnuplot","r") so that a sin graph is plotted when I execute the code. But i dont know how to pass multiple commands.Please tell me how can I pass multiple commands using popen.Please help thanks?

Here is the code which I am using to send single command:

#include <stdio.h>

int main()
{
    FILE *fp;
    int status;
    fp = popen("gnuplot","r");

    pclose(fp);

    return 0;
}

标签: c gnuplot popen
2条回答
家丑人穷心不美
2楼-- · 2019-07-21 21:52

Once you have called popen(), your file descriptor 'fp' is open and allows you to write data through it which the gnuplot command will see as input. Note that the type should be what you want to do with the pipe, not what the command will do with it, so you should use 'w' since you want to write. And you can issue multiple commands in sequence until you're done.

For example:

#include <stdio.h>

int main()
{
    FILE *fp;
    int status;
    fp = popen("gnuplot","w");
    fprintf(fp, "plot sin(x)\n");
    fprintf(fp, "plot tan(x)\n");

    pclose(fp);

    return 0;
}

Will send "sin(x)" and "tan(x)" followed by newlines through the pipe where gnuplot can read it as input.

查看更多
我命由我不由天
3楼-- · 2019-07-21 21:55

You should write, not read, to gnuplot, so try:

FILE *fp = popen("gnuplot","w");
if (!fp) { perror("popen gnuplot"); exit(EXIT_FAILURE); };
fprintf(fp, "plot sin(x)/x\n");
fflush(fp);

Don't forget to pclose(fp) where you are done. But this will probably close the plotted graph. See the §7.8 question of gnuplot FAQ

查看更多
登录 后发表回答