在C语言中如何运行系统命令并获取输出?

172

我想在Linux中运行一个命令并获取它的输出文本,但不希望将这些文本打印到屏幕上。是否有比创建临时文件更加优雅的方法?

2个回答

317
你需要使用 "popen" 函数。以下是运行命令 "ls /etc" 并将输出显示在控制台上的示例。
#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

1
将stderr重定向到stdout可能是个好主意,这样你就可以捕获错误。 - user25148
13
你应该使用fgets(path, sizeof(path), fp)而不是sizeof(path)-1。阅读手册。 - user102008
4
你可以在通过popen运行的shell命令中将stderr重定向到stdout,例如:fp = popen("/bin/ls /etc/ 2>&1", "r"); - rakslice
1
似乎可以使用popen进行双向通信,如果我发出一个需要用户确认的命令,那么我会得到提示。如果我只想读取输出,而不想有提示,我该怎么办? - Sachin
谢谢!非常有帮助。顺便提一下,似乎int status没有被使用。不是什么大问题。编辑:我已经移除了它。 - arr_sea
显示剩余3条评论

5
你需要一些进程间通信。可以使用管道或共享缓冲区。请参考 pipe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接