C++ 管道增压::iostreams don';我没有任何产出

C++ 管道增压::iostreams don';我没有任何产出,c++,boost,pipe,C++,Boost,Pipe,我正在尝试将管道与boost库一起使用,我只想执行一个后台程序(例如:ls)并以字符串形式获取其输出(就像您可以使用fopen和fread那样),但我真的不明白为什么我没有使用此代码的输出: #include <iostream> #include <cstdio> #include <sstream> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/devic

我正在尝试将管道与boost库一起使用,我只想执行一个后台程序(例如:ls)并以字符串形式获取其输出(就像您可以使用fopen和fread那样),但我真的不明白为什么我没有使用此代码的输出:

#include <iostream>
#include <cstdio>
#include <sstream>

#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>

int
main(int argc, char** argv)
{
    using namespace boost::iostreams;

    if(argc < 2)  {
        return -1;
    }

    FILE* p = popen(argv[1], "r");

    if(! p)  {
        std::cerr << "error open pipe" << std::endl;

        return -2;
    }

    int fd = fileno(p);
    std::stringstream ss;
    ss << fd;
    std::string s = ss.str();

    file_descriptor_source pdesc(s);
    stream_buffer<file_descriptor_source> pstream(pdesc);

    std::istream is(&pstream);
    std::string out;

    while(is)  {
        std::getline(is, out);
        std::cout << out << std::endl;
    }

    pstream.close();
    pdesc.close();
    pclose(p);

    return 0;
}
#包括
#包括
#包括
#包括
#包括
int
主(内部argc,字符**argv)
{
使用名称空间boost::iostreams;
如果(argc<2){
返回-1;
}
文件*p=popen(argv[1],“r”);
如果(!p){

std::cerr似乎您正试图从包含文件描述符编号的“路径”打开
boost::file\u descriptor\u source
。但是,此名称的文件可能不存在。您可能打算使用的是这样的文件:

if (FILE* p = popen(argv[1], "r")) 
{
    boost::iostreams::file_descriptor_source d(fileno(p), boost::iostreams::close_handle);
    boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_source> pstream(d);
    std::cout << &pstream;
    pclose(p);
}
if(文件*p=popen(argv[1],“r”))
{
boost::iostreams::文件描述符\源d(fileno(p),boost::iostreams::close\句柄);
boost::iostreams::流缓冲区pstream(d);

std::cout这可能与您当前的问题无关,但是您的读取循环错误地测试了eof/失败。习惯用法是先读取,然后测试;您的代码先测试,然后读取。因此,您应该执行
while(is){getline(is,out);…}
,而不是
while(getline(is,out)){…