I wanna write boost::asio app which is reading from stdin with boost::asio::streambuf. Anyway the only function which works on streambuf made from STDIN_FILENO is boost::asio::async_read_until. The other ones throws errors. Is there any possibility to read 100 first character from stdin with boost asio function?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
In principle this just works
#include <boost/asio.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
using namespace boost::asio;
using boost::system::error_code;
#include <iostream>
int main()
{
io_service svc;
posix::stream_descriptor in(svc, STDIN_FILENO);
char buf[100];
async_read(in, buffer(buf,sizeof(buf)), [&](error_code ec, size_t br) {
std::cout << std::string(buf, br) << std::flush;
if (ec)
std::cerr << ec.message();
});
svc.run();
}
When used as
cat input.txt | ./test | wc -c
will just output 100
as expected (and echo the input). We can even use live terminal input:
./test | wc -c
When the input is shorter than 100 bytes, you get the ec.message()
"End of file" printed too.
What does not work on Linux is:
./test < input.txt
you receive:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >'
what(): assign: Operation not permitted
This is because regular files are not supported for async operations: Strange exception throw - assign: Operation not permitted