从 C 读取 linux 命令的输出

Reading the output of a linux command from C

我有一个 C 程序使用 Linux 终端到 运行 python 程序,但我想确保 python 程序 运行s 没有错误。如果python程序在运行后终端打印错误信息,我希望C程序知道

run.py:

g = input(">")

if (g == 0):
    print("error")
    exit(1)
else:
    print("good")
    exit(0)

checker.c:

#include <stdio.h>
#include <stdlib.h>


int main(void){
    char run[30];
    snprintf(run, 30, "sudo python2.7 run.py");
    // I need to make sure that the next statement is run without errors
    system(run);

-正如我在评论中所说,您可以使用系统管道命令而不是使用 system popen|.

使用管道命令意味着将一个程序的输出(stdout)重定向到另一个程序的输入(stdin)。

我在下面插入的简单程序 (program_that_monitors) 在控制台上重写了另一个程序生成的所有输出 ( program_to_monitor) 管道(管道是 | )。

从命令行:

prog_to_monitor | program_that_monitors

使用这个简单的命令,要让 stderr 也有,有必要将其重定向到 stdout。一切都很简单:

从命令行:

prog_to_monitor 2>&1 | program_that_monitors

其中 2>&1stderr 重定向到 stdout 并且 | 执行从 program_to_monitor 到 program_that_monitors

的流水线操作

显然,您可以插入您的控制逻辑,而不是重写来自 program_to_monitor 的输出的部分。

这是非常简单的 C 代码:

#include <stdio.h>
#include <string.h>
int main()
{
    char buff[1000];

    while( fgets(buff, 1000, stdin) ) {
        printf(">> ");
        fwrite(buff,1,strlen(buff),stdout);
    }

    return 0;
}