如何在 C 中捕获进程输出?

Xim*_*mik 5 c unix linux posix system

有没有用 C 语言模拟 PHP 系统的情况?

man system说,system返回命令的状态,但我需要输出(就像在 PHP 中一样)。

当然,我可以使用管道来实现这一点,但是有什么标准的方法吗?

cod*_*ict 4

您可以使用popen和相关函数:

// command to be run.
char *cmd = "date"; 

// open pipe stream.
FILE *fp = popen(cmd,"r");
int ch; 

// error checking.
if(!fp) {
        fprintf(stderr,"Error popen with %s\n",cmd);
        exit(1);
}   

// read from the process and print.
while((ch = fgetc(fp)) != EOF) {
        putchar(ch);
}

// close the stream.
pclose(fp);
Run Code Online (Sandbox Code Playgroud)

IDEONE 链接