在C++中从外部程序中捕获stderr和stdout

Ham*_*JML 5 c++ linux

我正在尝试编写一个运行外部程序的程序.

我知道我可以抓住stdout,我可以一起抓住stdout,stderr但问题是我可以抓住stderrstdout分开吗?

我的意思是,例如,stderr变量STDERRstdout变量STDOUT.我的意思是我希望他们分开.

另外,我需要在变量中输出外部程序的退出代码.

glc*_*der 2

在 Windows 上,您必须填写STARTUPINFO捕获CreateProcess标准流,并且可以使用GetExitCodeProcess函数来获取终止状态。有一个示例如何将标准流重定向到父进程http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499.aspx

在类似 Linux 的操作系统上,您可能想要使用fork而不是execve,并且使用分叉进程是另一回事。

在 Windows 和 Linux 中,重定向流具有通用方法 - 您必须创建多个管道(每个流一个)并将子进程流重定向到该管道,并且父进程可以从该管道读取数据。

Linux 的示例代码:

int fd[2];

if (pipe(fd) == -1) {
    perror("pipe");
    exit(EXIT_FAILURE);
}

pid_t cpid = fork();
if (cpid == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
}

if (cpid == 0) { // child
    dup2(fd[1], STDERR_FILENO);
    fprintf(stderr, "Hello, World!\n");
    exit(EXIT_SUCCESS);
} else { // parent
    char ch;
    while (read(fd[0], &ch, 1) > 0)
        printf("%c", ch);
    exit(EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)

编辑:如果您需要从另一个程序捕获流,请使用与上面相同的策略,首先fork,第二个 - 使用管道(如上面的代码所示),然后execve在子进程中使用另一个程序并在父进程中使用此代码来等待执行结束并捕获返回码:

int status;
if (waitpid(cpid, &status, 0) < 0) {
    perror("waitpid");
    exit(EXIT_FAILURE);
}
Run Code Online (Sandbox Code Playgroud)

您可以在手册页pipelinedup2waitpid中找到更多详细信息。