2017-12-03 9 views
1

私は、async_readを子プロセスに接続してasync_readを実行しようとしている私の実際のコードから単純化した次のコードを持っています。子プロセスで私は "ls"と呼んでいます。単なるテストとして、私はその結果を得るために私の非同期の読み込みをしたい。それは次を返しますasync_readに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' ilを使用すると便利です。 – sehe

答えて

1

はあなたが0バイトの読み込みサイズ0

のベクトルに読み込みます。それがあなたが求めていたものです。

私はstreambufを使用し、EOFまで読んでみることをお勧めします。例えば

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(); 
} 

版画:あなたは本当にrun()が戻ることはありませんしたくなかったしない限り、また、workをドロップ

End of file 
15 
a.out 
main.cpp 
関連する問題