[英]async_read on async_pipe child process giving no data
我有以下代碼,這些代碼與我嘗試在連接到子進程的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()
永不返回:
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.