【问题标题】:Boost asio - async reading established number of chars from stdinBoost asio - 从标准输入异步读取已建立的字符数
【发布时间】:2014-05-18 08:58:05
【问题描述】:

我想编写 boost::asio 应用程序,它使用 boost::asio::streambuf 从标准输入读取。无论如何,唯一适用于由 STDIN_FILENO 生成的 streambuf 的函数是 boost::asio::async_read_until。其他的抛出错误。是否有可能使用 boost asio 功能从标准输入读取 100 个第一个字符?

【问题讨论】:

  • 向我们展示您的代码并告诉我们您看到了什么错误。

标签: boost boost-asio stdin


【解决方案1】:

原则上这是可行的

#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(并回显输入)。我们甚至可以使用实时终端输入:

./test | wc -c

当输入短于 100 字节时,您还会打印出ec.message()“文件结尾”。

在 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

这是因为异步操作不支持常规文件:Strange exception throw - assign: Operation not permitted

【讨论】:

    最近更新 更多