简体   繁体   English

如何在 C 中使用 popen 传递多个命令?

[英]How to pass multiple commands using popen in C?

I am trying to plot graphs using GNUPLOT which is a command line interface.我正在尝试使用命令行界面GNUPLOT绘制图形。 But I need to integrate it in c program, so that if program gets executed, graph is plotted.但是我需要将它集成到 c 程序中,这样如果程序被执行,就会绘制图形。 This can be done by using popen command.这可以通过使用popen命令来完成。 I have made a code where I am doing popen("gnuplot","r") so now when I execute the program, gnuplot starts.我已经制作了一个代码,我正在做popen("gnuplot","r")所以现在当我执行程序时,gnuplot 启动。 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.但是我需要在popen("gnuplot","r")之后发送多个命令,如popen("sin(x)","r") popen("gnuplot","r")以便在执行代码时绘制正弦图。 But i dont know how to pass multiple commands.Please tell me how can I pass multiple commands using popen .Please help thanks?但我不知道如何传递多个命令。请告诉我如何使用popen传递多个命令。请帮忙谢谢?

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

You should write, not read, to gnuplot , so try:您应该写入而不是读取gnuplot ,因此请尝试:

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.不要忘记在你完成的地方pclose(fp) But this will probably close the plotted graph.但这可能会关闭绘制的图形。 See the §7.8 question of gnuplot FAQ参见gnuplot FAQ的 §7.8 问题

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.一旦您调用了 popen(),您的文件描述符“fp”就会打开,并允许您通过它写入数据,gnuplot 命令会将这些数据视为输入。 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.请注意,类型应该是您要对管道执行的操作,而不是命令将对其执行的操作,因此您应该使用 'w' ,因为您要编写。 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.将通过管道发送“sin(x)”和“tan(x)”,然后是换行符,gnuplot 可以将其作为输入读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM