async_read async_pipe 子进程未提供数据

async_read on async_pipe child process giving no data

我有以下代码,它是从我的真实代码中简化而来的,我试图在连接到子进程的 async_pipe 上执行 async_read。在子进程中,我调用 "ls ." 只是一个测试,我希望我的异步读取能够得到结果。它returns以下

$ ./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 的向量。

您读取了 0 个字节。这就是你要的。

我建议使用 streambuf 并只读到 EOF。此外,删除 work 除非你真的希望 run() 永远不会 return:

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