[英]Getting shell command output in c++ before it ends running
Is there anyway to get the command stdout and stderr output before it ends running? 无论如何,在结束运行之前是否可以获得命令stdout和stderr输出? I've been trying
popen
and here's the code: 我一直在尝试
popen
,这是代码:
string exec(const char* cmd) {
char buffer[128];
string result;
string modCmd = (string)cmd + (string)" 2>&1";
FILE* pipe = popen(modCmd.c_str(), "r");
if (!pipe) throw runtime_error("popen() failed!");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != nullptr)
{
result += buffer;
cout << buffer;
}
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
but the problem is, all the cout
s stack up and run after the command's running is over. 但是问题是,所有
cout
都将在命令运行结束后堆叠并运行。
PS The command I'm trying to execute is aria2c PS我试图执行的命令是aria2c
如@VTT所述,问题是aria2c不会刷新其输出,但是有一种解决方法是运行stdbuf -o0 aria2c
而不是运行aria2c ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.