我正在使用Boost.Asio 1.78,我不能将file_stream::async_read_some
与任何方法一起使用,也不能使其在Asio中工作。
对于co_await,它抛出一个22, Invalid argument
,而对于任何其他方法,它都不会运行。我使用的是Ubuntu 20.04,我从https://github.com/quickemu-project/quickemu
这是读取文件协同程序:
boost::asio::awaitable<boost::container::vector<std::byte>> read_file_async(
boost::asio::any_io_executor & exe,
const std::filesystem::path & p) {
using boost::asio::use_awaitable;
boost::asio::stream_file file(exe, p.c_str(),
boost::asio::file_base::read_only | boost::asio::file_base::exclusive);
if (!file.is_open()) {
throw std::runtime_error(fmt::format("Could not open {}", p._c_str()));
}
constexpr std::size_t block_size = 1024 * 1024 * 2;
boost::container::vector<std::byte> buf(block_size, boost::container::default_init);
std::size_t curr_pos = 0;
std::size_t bytes_read = 1;
std::vector<std::byte> v(block_size);
while (bytes_read > 0) {
try {
bytes_read = co_await file.async_read_some(boost::asio::buffer(buf.data() + curr_pos,
buf.size() - curr_pos),
use_awaitable);
curr_pos += bytes_read;
if (curr_pos == buf.size())
buf.resize(buf.size() * 2, boost::container::default_init);
}
catch (const boost::system::system_error & e) {
fmt::print("{}n", e.what());
throw;
}
}
buf.resize(curr_pos, boost::container::default_init);
buf.shrink_to_fit();
co_return std::move(buf);
}
这是调用读取文件协同程序的代码:
boost::asio::io_context ctx;
auto the_task =
[&](std::filesystem::path p) -> boost::asio::awaitable<void> {
boost::asio::any_io_executor executor = co_await boost::asio::this_coro::executor;
auto file_contents = co_await read_file_async(executor, p);
};
for (const auto &file_path : rng)
boost::asio::co_spawn(ctx, the_task(file_path), boost::asio::detached);
ctx.run();
我遇到一个问题,因为epoll
被禁用,所以file_stream::async_read_some
和file_stream::async_write_some
的完成处理程序没有完成。
我遵循了此处的说明,设置了BOOST_ASIO_HAS_IO_URING
,但没有设置BOOST_ASIO_DISABLE_EPOLL
。现在我的完成处理程序,正确完成。