c++ - 如何捕获在 C++ 中运行的命令的 exit_code 和 stderr?

标签 c++ popen stderr exit-code

我正在编写一个 c++ 程序,它执行和输出(实时)一个 shell 脚本、makefile 或只是另一个程序。但是,当有错误或没有错误时,我希望我的程序以不同的方式返回。

#include "execxi.h"



using namespace std;


int execXI::run(string command)
{

    FILE *in;
    char buff[512];
    // is this the check for command execution exited with not 0?
    if(!(in = popen(command.c_str(), "r"))){
            // I want to return the exit code and error message too if any
        return 1;
    }
    // this part echoes the output of the command that's executed
    while(fgets(buff, sizeof(buff), in)!=NULL){
        cout << buff;
    }
    pclose(in);
    return 0;



}

是我目前所拥有的。

假设这个脚本运行 make 来构建一个程序,它给出了这样的错误

on_target_webkit_version out/Release/obj/gen/webkit_version.h
Traceback (most recent call last):
  File "../build/webkit_version.py", line 107, in <module>
    sys.exit(main())
  File "../build/webkit_version.py", line 103, in main
    return EmitVersionHeader(*sys.argv[1:])
  File "../build/webkit_version.py", line 86, in EmitVersionHeader
    webkit_revision = GetWebKitRevision(webkit_dir, version_file)
  File "../build/webkit_version.py", line 60, in GetWebKitRevision
    version_info = lastchange.FetchVersionInfo(
AttributeError: 'module' object has no attribute 'FetchVersionInfo'
make: *** [out/Release/obj/gen/webkit_version.h] Error 1
  • 我有可能知道这退出时出错了吗?

    • 是否会以代码 else than 0 退出,因为这是一个错误?

    • 最后一部分是在 stderr 中输出的吗?

考虑到 make 退出时的代码不是 0,比如说 1,它在 stderr 中的输出是我最终无法捕获这些退出代码和错误消息吗?

如何在程序输出结果后捕获退出代码和stderr,并在exit code/stderr中返回功能?

最佳答案

如果您对错误代码感兴趣,这是一种更便携的获取方式,而不是除以 256:

printf("Exit code: %i\n", WEXITSTATUS(pclose(fp)));

但是,popen 是一种方法,因此您要么通过 shell 中通常的重定向样式创建进一步的解决方法,要么按照此未经测试的代码正确执行:

#include <unistd.h>
#include <stdio.h>

/* since pipes are unidirectional, we need two pipes.
   one for data to flow from parent's stdout to child's
   stdin and the other for child's stdout to flow to
   parent's stdin */

#define NUM_PIPES          2

#define PARENT_WRITE_PIPE  0
#define PARENT_READ_PIPE   1

int pipes[NUM_PIPES][2];

/* always in a pipe[], pipe[0] is for read and 
   pipe[1] is for write */
#define READ_FD  0
#define WRITE_FD 1

#define PARENT_READ_FD  ( pipes[PARENT_READ_PIPE][READ_FD]   )
#define PARENT_WRITE_FD ( pipes[PARENT_WRITE_PIPE][WRITE_FD] )

#define CHILD_READ_FD   ( pipes[PARENT_WRITE_PIPE][READ_FD]  )
#define CHILD_WRITE_FD  ( pipes[PARENT_READ_PIPE][WRITE_FD]  )

void
main()
{
    int outfd[2];
    int infd[2];

    // pipes for parent to write and read
    pipe(pipes[PARENT_READ_PIPE]);
    pipe(pipes[PARENT_WRITE_PIPE]);

    if(!fork()) {
        char *argv[]={ "/usr/bin/bc", "-q", 0};

        dup2(CHILD_READ_FD, STDIN_FILENO);
        dup2(CHILD_WRITE_FD, STDOUT_FILENO);

        /* Close fds not required by child. Also, we don't
           want the exec'ed program to know these existed */
        close(CHILD_READ_FD);
        close(CHILD_WRITE_FD);
        close(PARENT_READ_FD);
        close(PARENT_WRITE_FD);

        execv(argv[0], argv);
    } else {
        char buffer[100];
        int count;

        /* close fds not required by parent */       
        close(CHILD_READ_FD);
        close(CHILD_WRITE_FD);

        // Write to child’s stdin
        write(PARENT_WRITE_FD, "2^32\n", 5);

        // Read from child’s stdout
        count = read(PARENT_READ_FD, buffer, sizeof(buffer)-1);
        if (count >= 0) {
            buffer[count] = 0;
            printf("%s", buffer);
        } else {
            printf("IO Error\n");
        }
    }
}

代码来自这里:

http://jineshkj.wordpress.com/2006/12/22/how-to-capture-stdin-stdout-and-stderr-of-child-program/

关于c++ - 如何捕获在 C++ 中运行的命令的 exit_code 和 stderr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15058876/

相关文章:

c++ - 一种按索引过滤范围,仅从过滤后的索引中获取 min_element 的方法?

c++ - 将 typeid 转换为命名空间以进行静态成员访问 (C++)

C - fgets 奇怪的行为

python - 使用 Popen 打开进程并获取 PID

stdout - 将 SystemVerilog $display 发送到 stderr

c++ - 如何将点击从一个Qt小部件转移到另一个?

c++ - NetUserAdd - 权限问题,参数不正确

python - 当我从作为 Linux 服务运行的 python 脚本调用它时,Popen 无法启动进程

python - 记录标准输出,但在每个条目上得到第二个空行

c++ - 如何将 stderr/stdout 重定向到我在 C++ 中的登录?