async_read on async_pipe子进程没有提供数据

async_read on async_pipe child process giving no data

本文关键字:async 提供数据 pipe read on 子进程      更新时间:2023-10-16

我具有以下代码,从我的真实代码中简化了我试图在连接到子过程的async_pipe上进行async_read。在孩子过程中,我称为" LS"。作为一个测试,我希望我的异步阅读以获得结果。它返回以下

$ ./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()永远不会返回:

活在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