【问题标题】:Replacing select() with boost::asio::io_service用 boost::asio::io_service 替换 select()
【发布时间】:2017-09-05 19:21:32
【问题描述】:

我正在尝试用boost::asio::io_service.run() 替换我程序中的主循环(while(1)...select())。 该程序打开了几个套接字,由 select() 监视。

棘手的部分是 select 语句中的 FD_SET 具有套接字文件描述符以及 char 设备描述符(用于硬件输入)。在前面的代码中,调用int fd = open("/dev/button1", O_RDONLY); 就足够了,并且那个fd 被添加到了FD_SET 中。 select() 语句可以监控所有这些。

所以为了能够从boost::asio::io_service 监控字符设备,我已经阅读了很多关于boost::asio::stream_descriptor 的信息。但我无法让它工作。

我已经尝试正常打开设备,然后创建一个stream_descriptor,并将其添加到ioservice。

void callback(const boost::system::error_code &ec, std::size_t bytes){
    std::cout << "callback called" << std::endl;
}
int main() {
    static boost::asio::streambuf buffer;
    int fd = open("/dev/button1", O_RDONLY);
    boost::asio::posix::stream_descriptor btn(io_service, fd);
    boost::asio::async_read(btn, buffer, &button_callback);
    io_service.run();
}

但是,这不起作用。

【问题讨论】:

  • 您是否考虑过使用poll(2) 而不是select
  • btn 是否可能在 async_read 真正发挥作用之前直接超出范围(当 io_service 运行时),因此它被破坏并且从未调用过回调?我们只能猜测,显示的代码看起来没问题,错误可能在其他地方。

标签: c++ boost-asio


【解决方案1】:

您没有显示任何运行 io_servicerun()poll()run_one()poll_one())的代码。所以什么都做不了。

使用流描述符从/dev/inputN 读取的具体示例如下:

boost::asio read from /dev/input/event0

它只是使用::open 打开设备(在本例中为/dev/input/event2,但它只是一个您可以更改的文件名)。

注意它如何调用io_service::run()

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 2011-06-16
    • 2017-09-17
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多