简体   繁体   English

async_pipe子进程上的async_read不提供数据

[英]async_read on async_pipe child process giving no data

I have the following code which is simplified from my real code where I am trying to do an async_read on an async_pipe connected to a child process. 我有以下代码,这些代码与我尝试在连接到子进程的async_pipe上执行async_read的真实代码简化了。 In the child process I am calling "ls ." 在子进程中,我称“ ls”。 as just a test and I want my async read to get the result of that. 作为一个测试,我希望我的异步读取来获得结果。 It returns the following 它返回以下内容

$ ./a.out
system:0
0

Why does this happen I cannot figure out? 为什么我不知道会发生这种情况? Ideally I want to replace "ls ." 理想情况下,我要替换“ ls”。 with a long running process where I can read line after line with async_read. 运行很长时间,我可以用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();
}

You read into a vector of size 0. 您读入大小为0的向量。

You read 0 bytes. 您读取了0个字节。 That's what you asked for. 那就是你要的。

I'd suggest using a streambuf and just reading till EOF. 我建议使用streambuf并阅读直到EOF。 Also, drop work unless you really did want run() to never return: 另外,删除work除非您确实确实希望run()永不返回:

Live On Coliru 生活在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();
}

Prints, eg 印刷品,例如

End of file
15
a.out
main.cpp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM