2017-06-18 85 views
2

我正在編寫一個需要打開另一個進程並獲取它的輸出的應用程序。在線閱讀我不得不使用popen並從文件中讀取。 但我無法讀取它。命令get的輸出輸出到調用應用程序的控制檯窗口中。以下是我正在使用的代碼。我添加了一些打印來調試。popen()將執行的命令輸出寫入到cout中

#include <string> 
#include <iostream> 
#include <cstdlib> 
#include <cstdio> 
#include <array> 

int main() 
{ 
    // some command that fails to execute properly. 
    std::string command("ls afskfksakfafkas"); 

    std::array<char, 128> buffer; 
    std::string result; 

    std::cout << "Opening reading pipe" << std::endl; 
    FILE* pipe = popen(command.c_str(), "r"); 
    if (!pipe) 
    { 
     std::cerr << "Couldn't start command." << std::endl; 
     return 0; 
    } 
    while (fgets(buffer.data(), 128, pipe) != NULL) { 
     std::cout << "Reading..." << std::endl; 
     result += buffer.data(); 
    } 
    auto returnCode = pclose(pipe); 

    std::cout << result << std::endl; 
    std::cout << returnCode << std::endl; 

    return 0; 
} 

閱讀是從來沒有實際打印到我的cout和結果是一個空字符串。我清楚地看到命令在我終端中的輸出......如果命令正常退出,行爲如預期。但我只捕獲錯誤情況下的輸出。

我希望有人能幫忙!

+0

使用'FEOF()',以控制迴路是不好的做法,並且在你的情況下毫無意義,因爲'fgets()'在文件結尾處返回NULL。嘗試提供人們可以用來重新創建問題的[mcve]。如果您不知道問題出在哪裏,那麼提供像您這樣的部分信息是避免出現重要信息的好方法。您正在運行的命令很可能使用了不能使用您的技術進行重定向的輸出方式。 – Peter

+0

@Peter 提供完整示例。我從字面上只是添加int main並添加了一個硬編碼命令... –

回答

0

Popen不捕獲stderr只有stdout。將stderr重定向到stdout可以解決問題。

#include <string> 
#include <iostream> 
#include <cstdlib> 
#include <cstdio> 
#include <array> 

int main() 
{ 
    std::string command("ls afskfksakfafkas 2>&1"); 

    std::array<char, 128> buffer; 
    std::string result; 

    std::cout << "Opening reading pipe" << std::endl; 
    FILE* pipe = popen(command.c_str(), "r"); 
    if (!pipe) 
    { 
     std::cerr << "Couldn't start command." << std::endl; 
     return 0; 
    } 
    while (fgets(buffer.data(), 128, pipe) != NULL) { 
     std::cout << "Reading..." << std::endl; 
     result += buffer.data(); 
    } 
    auto returnCode = pclose(pipe); 

    std::cout << result << std::endl; 
    std::cout << returnCode << std::endl; 

    return 0; 
}