使用boost async_read和posix :: stream_descriptor从键盘读取 [英] read from keyboard using boost async_read and posix::stream_descriptor

查看:202
本文介绍了使用boost async_read和posix :: stream_descriptor从键盘读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to capture single keyboard inputs in a non blocking way inside a while loop using boost asio async_read. The handler is expected to display the read characters.

我的代码:

    #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格式):

My output is not as expected(keyinput=char format):

a
key input
b
c
d
e

我要去哪里错了?

该程序也是非常占用CPU的.该如何纠正?

Also the program is very cpu intensive. How to rectify it?

推荐答案

使用stdin的异步IO有一个重要限制:

There's an important restriction on async IO with stdin: Strange exception throw - assign: Operation not permitted

第二,如果您使用 async_read ,请不要同时使用 std :: cin (您将只进行两次读取).(请查看 async_wait ).

Secondly, if you use async_read do not use std::cin at the same time (you will just do two reads). (Do look at async_wait instead).

此外,您应该能够通过正确使用异步IO来解决CPU高负载的问题:

That aside, you should be able to fix the high CPU load by using async IO properly:

#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 循环已被一系列异步操作取代.

As you can see the while loop has been replaced with a chain of async operations.

这篇关于使用boost async_read和posix :: stream_descriptor从键盘读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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