使用boost async_read和posix :: stream_descriptor从键盘读取

问题描述 投票:1回答:1

我试图使用boost asio async_read在while循环内以非阻塞方式捕获单个键盘输入。处理程序应显示读取的字符。

我的代码:

    #include <boost/asio/io_service.hpp>
    #include <boost/asio/posix/stream_descriptor.hpp>
    #include <boost/asio/read.hpp>
    #include <boost/system/error_code.hpp>
    #include <iostream>
    #include <unistd.h>
    #include <termios.h>

    using namespace boost::asio;

    void read_handler(const boost::system::error_code&, std::size_t)
    {   
        char c;
        std::cin>>c;

        std::cout << "keyinput=" << c << std::endl;
    }

    int main()
    {
      io_service ioservice;        
      posix::stream_descriptor stream(ioservice, STDIN_FILENO);

      char buf[1];
      while(1)
      {    
      async_read(stream, buffer(buf,sizeof(buf)), read_handler);
      ioservice.run();    
      }     
      return 0;    
    }

我的输出不符合预期(keyinput = char格式):

a
key input
b
c
d
e

我哪里错了?

该程序也非常密集。如何纠正呢?

c++ keyboard boost-asio nonblocking
1个回答
1
投票

使用stdin:Strange exception throw - assign: Operation not permitted对异步IO有一个重要的限制

其次,如果你使用async_read不要同时使用std::cin(你只需要做两次读取)。 (请看看async_wait)。

除此之外,您应该能够通过正确使用异步IO来修复高CPU负载:

#include <boost/asio.hpp>
#include <iostream>

using namespace boost::asio;

int main()
{
    io_service ioservice;        
    posix::stream_descriptor stream(ioservice, STDIN_FILENO);

    char buf[1] = {};

    std::function<void(boost::system::error_code, size_t)> read_handler;

    read_handler = [&](boost::system::error_code ec, size_t len) {   
            if (ec) {
                std::cerr << "exit with " << ec.message() << std::endl;
            } else {
                if (len == 1) {
                    std::cout << "keyinput=" << buf[0] << std::endl;
                }
                async_read(stream, buffer(buf), read_handler);
            }
        };


    async_read(stream, buffer(buf), read_handler);

    ioservice.run();    
}

正如您所看到的,while循环已被一系列异步操作所取代。

© www.soinside.com 2019 - 2024. All rights reserved.