在结束运行之前获取 c++ 中的 shell 命令输出



在命令停止运行之前,有没有办法获取命令标准输出和标准输出? 我一直在尝试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;
}

但问题是,所有cout都会堆叠起来,并在命令运行结束后运行。
附言我尝试执行的命令是 aria2c

正如@VTT提到的,问题在于 aria2c 不会刷新其输出,但有一种解决方法是运行stdbuf -o0 aria2c而不是运行aria2c ...

最新更新