簡體   English   中英

在結束運行之前在C ++中獲取Shell命令輸出

[英]Getting shell command output in c++ before it ends running

無論如何,在結束運行之前是否可以獲得命令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都將在命令運行結束后堆疊並運行。
PS我試圖執行的命令是aria2c

@VTT所述,問題是aria2c不會刷新其輸出,但是有一種解決方法是運行stdbuf -o0 aria2c而不是運行aria2c ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM