在C程序中获取系统命令输出

有没有更好的方法来做到这一点?

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"); 

我不想创build中间文件,然后删除它。

编辑:

它不是从文件读取。 该命令可以是“ls”或“echo”Hello world“”

好吧,我在另一个答案中感到困惑。 无论如何,这个答案中的哲学是一样的。 你可以直接使用popen函数。

那么你有这样的东西:

 int numOfCPU; FILE *fp = popen("grep -c ^processor /proc/cpuinfo", "r"); fscanf(fp, "%d", &numOfCPU); pclose(fp); 

我希望这会有用。

你需要使用重定向和管道来做你正在做的事情。

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

您应该修改子进程以使用dup2将标准输出重定向到管道,然后执行您希望运行的命令。

使用awk

 #include <stdlib.h> #include <stdio.h> void main() { int numOfCPU =0; system ("awk '/processor/{numOfCPU++}END{print numOfCPU}' /proc/cpuinfo"); }