This is an usage sample of how to call a sub-process and get its screen output.
1. main.cpp
2. sub.cpp
main will call sub-process sub, and get all its screen output.
g++ sub.cpp -o sub
g++ main.cpp -o main
case 1:
$ main Hello test stderr Bye test stderr line is [Hello test stdout] line is [Bye test stdout]
The stdout output can be caught by main process, but not stderr output.
case 2: redirect stderr to stdout
$ main line is [Hello test stderr] line is [Bye test stderr] line is [Hello test stdout] line is [Bye test stdout]
Appendix
sub.cpp
$ cat sub.cpp
#include <string>
#include <iostream>
int main(int argc, char * argv[]) {
fprintf(stdout, "Hello %s stdout\n", argc > 1 ? argv[1] : argv[0]);
fprintf(stdout, "Bye %s stdout\n", argc > 1 ? argv[1] : argv[0]);
fprintf(stderr, "Hello %s stderr\n", argc > 1 ? argv[1] : argv[0]);
fprintf(stderr, "Bye %s stderr\n", argc > 1 ? argv[1] : argv[0]);
return 1;
}
main.cpp
$ cat main.cpp
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <iostream>
int main(int argc, char * argv[]) {
std::string param = "test";
std::string cmd = "sub " + param;
//Or if you need both stdout and stderr
//std::string cmd = "sub " + param + " 2>&1";
FILE * fp = popen(cmd.c_str(), "r");
if (fp != NULL) {
char line[1024] = { '\0' };
while (fgets(line, 1024, fp) != NULL) {
char * pos = NULL;
if ((pos = strchr(line, '\n')) != NULL) {
// remove the newline char at the end
*pos = '\0';
}
std::cout << "line is [" << line << "]" << std::endl;
memset(line, '\0', 1024);
}
pclose(fp);
}
return 0;
}
Because library function popen can only give us a file handle on a process' stdout, not stderr; however we can redirect stdout and stderr.
The end
本文介绍了一种在C++中通过调用子进程并获取其标准输出的方法,并演示了如何同时捕获标准输出(stdout)和标准错误输出(stderr)。通过重定向stderr到stdout,可以确保所有输出都能被主进程捕获。
1838

被折叠的 条评论
为什么被折叠?



