Boost Asio-异步从stdin读取已建立的字符数 [英] Boost asio - async reading established number of chars from stdin

查看:151
本文介绍了Boost Asio-异步从stdin读取已建立的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写boost :: asio应用程序,该应用程序是通过boost :: asio :: streambuf从stdin读取的.无论如何,对STDIN_FILENO制成的streambuf起作用的唯一函数是boost :: asio :: async_read_until.其他的则抛出错误.有可能通过boost asio函数从stdin读取100个第一个字符吗?

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?

推荐答案

原则上这是可行的

#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();
}

用作

cat input.txt | ./test | wc -c

只会按预期输出100(并回显输入).我们甚至可以使用实时终端输入:

will just output 100 as expected (and echo the input). We can even use live terminal input:

./test | wc -c

当输入少于100个字节时,也会打印出ec.message()文件末尾".

When the input is shorter than 100 bytes, you get the ec.message() "End of file" printed too.

在Linux上不起作用的是:

 ./test < input.txt

您收到:

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

这篇关于Boost Asio-异步从stdin读取已建立的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆