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

时间:2018-05-30 09:32:36

标签: c++ command-line popen

在结束运行之前,是否有命令stdout和stderr输出? 我一直在尝试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 s堆叠并在命令运行结束后运行。
附:我试图执行的命令是aria2c

1 个答案:

答案 0 :(得分:2)

@VTT提到的问题是aria2c没有刷新它的输出,但是有一个解决方法是运行stdbuf -o0 aria2c而不是运行aria2c ... }