【问题标题】:How to send command to Linux command from C program如何从 C 程序向 Linux 命令发送命令
【发布时间】:2017-06-21 14:39:03
【问题描述】:

我正在尝试从 C 程序向 Linux 命令行发送命令,但有一部分我不知道该怎么做。

例如在我的 C 代码中

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

我希望能够在“图像”的末尾添加一个数字并在每次程序运行时递增它,但是我如何将变量 n 传递给 system() 函数只是在寻找const char

我试过了,但没用:

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

我已尝试对此进行搜索,但没有找到有关如何向其中添加变量的任何信息。对不起菜鸟问题。

【问题讨论】:

标签: c linux


【解决方案1】:
char fileName[80];

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

【讨论】:

  • 谢谢!这非常有效!我没有意识到 sprintf() 可以这样使用。
【解决方案2】:

首先,String 是一个 char 数组,所以声明(我想你知道,只是为了强调):

char command[32]; 

所以,简单的解决方案是:

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

然后拨打system(command);。这正是您所需要的。


编辑:

如果需要程序输出,试试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);

来源:C: Run a System Command and Get Output?

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

【讨论】: