2017-12-03 211 views
1

我有下面的代码,这是从我真正的代码简化,我试图做一个async_read连接到子进程的async_pipe。在孩子的过程中,我打电话给“ls”。只是一个测试,我希望我的异步阅读获得结果。它返回以下内容async_pipe async_pipe子进程没有给出数据

$ ./a.out 
system:0 
0 

为什么会发生这种情况我找不出来?理想情况下,我想替换“ls”。有一个长时间的运行过程,我可以在线阅读async_read。

#include <boost/asio.hpp> 
#include <boost/bind.hpp> 
#include <iostream> 
#include <fstream> 
#include <unistd.h> 
#include <string.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <boost/process.hpp> 

namespace bp = boost::process; 

class test { 
private: 
    boost::asio::io_service ios; 
    boost::asio::io_service::work work; 
    bp::async_pipe ap; 
    std::vector<char> buf; 

public: 
    test() 
    : ios(), work(ios), ap(ios) { 
    } 

    void read(
     const boost::system::error_code& ec, 
     std::size_t size) { 
    std::cout << ec << std::endl; 
    std::cout << size << std::endl; 
    } 

    void run() { 
    bp::child c(bp::search_path("ls"), ".", bp::std_out > ap); 
    boost::asio::async_read(ap, boost::asio::buffer(buf), 
     boost::bind(&test::read, 
        this, 
        boost::asio::placeholders::error, 
        boost::asio::placeholders::bytes_transferred)); 

    ios.run(); 
    } 
}; 

int main() { 
    test c; 
    c.run(); 
} 
+0

通过'async_read_until'或'ap.read_some'这一行可以更方便地阅读行 – sehe

回答

1

您读入大小为0

的向量你读0字节。这就是你要求的。

我建议使用streambuf并且直到EOF读取。此外,降work除非你真的想run()永不返回:

Live On Coliru

#include <boost/asio.hpp> 
#include <boost/bind.hpp> 
#include <boost/process.hpp> 
#include <iostream> 

namespace bp = boost::process; 

class test { 
    private: 
    boost::asio::io_service ios; 
    bp::async_pipe ap; 
    boost::asio::streambuf buf; 

    public: 
    test() : ios(), ap(ios) {} 

    void read(const boost::system::error_code &ec, std::size_t size) { 
     std::cout << ec.message() << "\n"; 
     std::cout << size << "\n"; 
     std::cout << &buf << std::flush; 
    } 

    void run() { 
     bp::child c(bp::search_path("ls"), ".", bp::std_out > ap, ios); 

     async_read(ap, buf, boost::bind(&test::read, this, _1, _2)); 

     ios.run(); 
    } 
}; 

int main() { 
    test c; 
    c.run(); 
} 

打印,例如

End of file 
15 
a.out 
main.cpp