How to pass multiple commands using popen in C?

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

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

回答1:

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.



回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!