C语言 在C程序中获取系统命令输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17107365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get system command output in C program
提问by Vikas Goel
Is there a better way to do it?
有没有更好的方法来做到这一点?
int numOfCPU;
system("grep -c ^processor /proc/cpuinfo >> /tmp/cpuinfo");
FILE *fp = fopen("/tmp/cpuinfo", "r");
fscanf(fp, "%d", &numOfCPU);
fclose(fp);
system("rm /tmp/cpuinfo");
I don't want to create an intermediary file and then remove it.
我不想创建一个中间文件然后将其删除。
EDIT:
编辑:
Its not about reading from the file. The command can be "ls" or "echo 'Hello world'"
它不是关于从文件中读取。命令可以是“ls”或“echo 'Hello world'”
回答by castarco
Ok, I was confused in my other answer. In any case, the philosophy in this answer is the same. You can use directly the popenfunction.
好的,我在另一个答案中感到困惑。无论如何,这个答案的哲学是一样的。您可以直接使用popen函数。
Then you have something like this:
然后你有这样的事情:
int numOfCPU;
FILE *fp = popen("grep -c ^processor /proc/cpuinfo", "r");
fscanf(fp, "%d", &numOfCPU);
pclose(fp);
I hope it will be useful.
我希望它会很有用。
回答by LtWorf
You need to use redirection and pipes to do what you are trying to do.
你需要使用重定向和管道来做你想做的事情。
The popencall can help you, but if you want something more flexible, such as also redirecting input, or more secure, such as not running a string in the shell, you should follow this example, taking from the manual page of pipe.
该POPEN通话可以帮助你,但如果你想要的东西更灵活,比如也重新定向输入,或更安全,如没有运行在shell一个字符串,你应该遵循这个例子中,从管道的手册页服用。
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
You should modify the child process to use dup2 to redirect the standard output to the pipe and then exec the command you want it to run.
您应该修改子进程以使用 dup2 将标准输出重定向到管道,然后执行您希望它运行的命令。
回答by hazzelnuttie
Using awk:
使用 awk:
#include <stdlib.h>
#include <stdio.h>
void main()
{
int numOfCPU =0;
system ("awk '/processor/{numOfCPU++}END{print numOfCPU}' /proc/cpuinfo");
}

