C:运行系统命令并获取输出?

jim*_*rix 129 c linux system

可能重复:
如何从C运行外部程序并解析其输出?

我想在linux中运行一个命令,并返回它输出的文本,但我希望这个文本打印到屏幕上.有没有比制作临时文件更优雅的方式?

小智 233

你想要" 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用`fgets(path,sizeof(path),fp)`而不是`sizeof(path)-1`.阅读手册 (10认同)
  • @jimi:你可以在你通过popen运行的shell命令中将stderr重定向到stdout,例如fp = popen("/ bin/ls/etc/2>&1","r"); (2认同)

dir*_*tly 5

您需要某种进程间通信。使用管道或共享缓冲区。