简体   繁体   English

如何从C程序向Linux命令发送命令

[英]How to send command to Linux command from C program

I am trying to send a command to a Linux command line from a C program and there is one part I am not sure how to do. 我正在尝试从C程序向Linux命令行发送命令,但我不确定其中一部分是怎么做的。

For example in my C code I have 例如在我的C代码中

system("raspistill -o image.jpg");

What I would like to be able to do is add a number to the end of "image" and increment it every time the program runs, but how can I pass in a variable n to the system() function that is only looking for a const char ? 我想做的是在“图像”的末尾添加一个数字,并在每次程序运行时将其递增,但是我如何将变量n传递给仅寻找一个变量的system()函数呢? const char

I tried this but it did not work: 我试过了,但是没有用:

char fileName = ("raspistill -o image%d.jpg",n);
system(filename);

I've tried searching on this and haven't found anything about how to add a variable to it. 我已经尝试过搜索,但是还没有找到有关如何向其中添加变量的任何信息。 Sorry for the noob question. 对不起,菜鸟问题。

char fileName[80];

sprintf(fileName, "raspistill -o image%d.jpg",n);
system(filename);

First, a String is a char array, so declare (I think you know, just to emphasize): 首先,一个String是一个char数组,所以要声明(我想你只是想强调一下):

char command[32]; 

So, simple solution will be: 因此,简单的解决方案将是:

sprintf(command, "raspistill -o image%d.jpg", n);

Then call system(command); 然后调用system(command); . This is just what you need. 这正是您所需要的。


EDIT: 编辑:

If you need program output , try popen : 如果 需要程序输出 ,请尝试popen

char command[32]; 
char data[1024];
sprintf(command, "raspistill -o image%d.jpg", n);
//Open the process with given 'command' for reading
FILE* file = popen(command, "r");
// do something with program output.
while (fgets(data, sizeof(data)-1, file) != NULL) {
    printf("%s", data);
}
pclose(file);

Sources: C: Run a System Command and Get Output? 资料来源: C:运行系统命令并获取输出?

http://man7.org/linux/man-pages/man3/popen.3.html http://man7.org/linux/man-pages/man3/popen.3.html

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

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