【问题标题】:Reading the output of a linux command from C从 C 读取 linux 命令的输出
【发布时间】:2021-10-13 09:36:07
【问题描述】:

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

运行.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);

【问题讨论】:

  • 这可能有与 C 检查命令“sudo mv nonexistant.x”中的错误类似的解决方案,但我也不知道该怎么做
  • 试试popen。或者只是检查system() 的返回码。任何非零都表示错误。
  • 使用popen 是一种选择,但您可以编写一个C 程序在管道中使用。管道程序在标准输入上接收程序的输出。所以你可以在命令行中使用:pyprog | Cprog,通过这样做,C 程序将在标准输入上接收到 python 程序的所有输出。
  • 那里给出的代码在 C 中的工作方式相同。
  • 什么指示错误消息?在流stderr 上输出?有输出吗?以errorErrorERROR 或令牌Failure 开头的消息?还是只是子进程的返回值?在后一种情况下,man system 解释了调用的返回值。

标签: python c linux error-handling


【解决方案1】:

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

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

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

从命令行:

prog_to_monitor | program_that_monitors

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

从命令行:

prog_to_monitor 2>&1 | program_that_monitors

2&gt;&amp;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;
}

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多