2017-06-18 87 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; 
}