从外部程序中捕获标准和标准输出 C++.
Catch stderr and stdout from external program in C++
我正在尝试编写一个运行外部程序的程序。
我知道我可以抓住stdout
,我可以一起抓住stdout
和stderr
,但问题是我能抓住stderr
和stdout
分开吗?
我的意思是,例如,在变量STDERR
中stderr
,在变量STDOUT
中stdout
。我的意思是我希望他们分开。
我还需要在变量中输入外部程序的退出代码。
在 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 中找到更多详细信息。
相关文章:
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 使用提升过程获取 shell 命令的标准输出
- 将标准输出重定向到ostream
- 如何在C++中执行命令并获取命令的返回代码标准输出和标准
- 在程序执行期间从标准输出重定向到自定义流
- 标准输出C++意外行为
- 防止 qDebug() 写入标准输出
- C++ - <<运算符重载,链表 - 地址而不是标准输出
- 有没有办法知道C++中将打印到标准输出的大小?
- 最后推迟标准输出
- 得到~对标准输出没有回应~在黑客排名问题上
- Win32 GUI C(++) 应用将标准输出和标准输出重定向到磁盘上的同一文件
- 在标准输出中执行打印会导致数组中随机分配值
- 捕获远程进程子进程的标准输出
- 使用 QProcess 读取标准输出
- 如何将值发送到标准输出流并在另一个程序中访问这些值
- 无法使用创建进程重定向标准输出
- HackerRank说~对标准输出没有回应~.C++
- 记录标准输入和标准输出
- 我可以重定向两个子进程的标准输出吗?