5

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

我知道我可以抓住stdout,我可以抓住stdoutand stderrtogether 但问题是我能抓住stderrandstdout分开吗?

我的意思是,例如,stderr在变量STDERRstdout变量中STDOUT。我的意思是我想让他们分开。

我还需要变量中的外部程序的退出代码。

4

1 回答 1

2

在 Windows 上,您必须填写STARTUPINFOCreateProcess捕获标准流,并且您可以使用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);
}

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

int status;
if (waitpid(cpid, &status, 0) < 0) {
    perror("waitpid");
    exit(EXIT_FAILURE);
}

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

于 2012-10-24T08:22:05.577 回答