我正在嘗試使用 boost::asio::async_read 從管道中異步讀取,但它每次都讀取零位元組。但是,我可以使用 read 函式(unistd.h)成功地從管道中讀取;
這是我的代碼:
auto io = make_shared<boost::asio::io_service>();
auto work = make_shared<boost::asio::io_service::work>(*io);
int read_end = atoi(argv[0]);
auto pipe_read = make_shared<boost::asio::readable_pipe>(*io, read_end);
string message;
boost::thread_group worker_threads;
for(int i = 0; i < 1; i )
{
// I'm calling io->run() inside the worker thread.
worker_threads.create_thread(boost::bind(&workerThread, io));
}
// The handler function gets the number of bytes read, which is always zero.
boost::asio::async_read(*pipe_read, boost::asio::buffer(message, 5), boost::bind(&handler, _1, _2));
cout << message << endl;
work.reset();
worker_threads.join_all();
return 0;
任何幫助將非常感激。
uj5u.com熱心網友回復:
給定一個
std::string message;
然后asio::buffer(message)大小為 0(因為字串為空)。
采用大小的多載asio::buffer(message, 5)只能限制大小,但不提供。所以它仍然是大小 0。
這解釋了你的癥狀。反而,
std::string message(5, '\0');
auto b = asio::buffer(message);
或者,或者,
std::string message;
message.resize(1024); // cue Bill Gates miss-quote
auto b = asio::buffer(message, 5);
甚至使用動態緩沖區:
std::string message;
auto b = asio::dynamic_buffer(message/*, 5*/);
現場演示
展示一個現代化版本也修復了我所說的各種錯誤:
住在科利魯
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
namespace asio = boost::asio;
void handler(boost::system::error_code ec, size_t xfr) {
std::cout << "Received " << xfr << " bytes (" << ec.message() << ")\n";
}
int main(int argc, char** argv) {
asio::thread_pool ioc(1); // or more threads
assert(argc > 1);
int read_end = atoi(argv[1]);
auto pipe_read = make_shared<boost::asio::readable_pipe>(ioc, read_end);
std::string message(5, '\0');
boost::asio::async_read(*pipe_read, asio::buffer(message), &handler);
ioc.join();
std::cout << message << std::endl;
}
印刷
./a.out 0 <<< "HELLO WORLD"
Received 5 bytes (Success)
HELLO
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513476.html
上一篇:awk中的精確正則運算式匹配
