问题
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
来源:https://stackoverflow.com/questions/23720222/boost-asio-async-reading-established-number-of-chars-from-stdin