How to ensure that we read all lines from boost::child process

前端 未结 3 656
南方客
南方客 2021-02-08 21:16

I saw the following code on boost::child documentation page where they explain how to read the output of a child process. http://www.boost.org/doc/libs/1_64_0/doc/h

3条回答
  •  情深已故
    2021-02-08 21:56

    I think there's no proper way unless you use asynchronous methods.

    Perhaps you can simple get a future to a vector and use string_views into that if you somehow really need it line-by-line.

    std::future > output, error;
    
    boost::asio::io_service svc;
    bp::child c(bp::search_path("nm"), file, bp::std_out > output, bp::std_err > error, svc);
    svc.run();
    

    To read exactly like you did before you can use an istream on top of the vector:

    #include 
    #include 
    #include 
    #include 
    
    namespace bp = boost::process;
    namespace bio = boost::iostreams;
    std::string const file = "./a.out";
    
    int main() {
        std::future > output, error;
    
        boost::asio::io_service svc;
        bp::child c(bp::search_path("nm"), file, bp::std_out > output, bp::std_err > error, svc);
        svc.run();
    
        //then later
        {
            auto raw = output.get();
            std::vector data;
            std::string line;
            bio::stream_buffer sb(raw.data(), raw.size());
            std::istream is(&sb);
    
            while (std::getline(is, line) && !line.empty())
                data.push_back(line);
    
            std::cout << data.at(rand()%data.size()) << "\n";
        }
    
    }
    

提交回复
热议问题