从外部程序中捕获标准和标准输出 C++.

Catch stderr and stdout from external program in C++

本文关键字:标准输出 C++ 标准 程序 从外部      更新时间:2023-10-16

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

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

我的意思是,例如,在变量STDERRstderr,在变量STDOUTstdout。我的意思是我希望他们分开。

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

在 Windows 上,您必须为CreateProcess填充STARTUPINFO才能捕获标准流,并且您可以使用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另一个 progrram 并在父进程中使用此代码等待执行结束并捕获返回代码:

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

您可以在 man page pipe、dup2 和 waitpid 中找到更多详细信息。