我正在尝试用 while(1)...select()
替换我程序中的主循环 ( boost::asio::io_service.run()
) .
该程序有几个打开的套接字,由 select() 监视。
棘手的部分是 select 语句中的 FD_SET 具有套接字文件描述符以及字符设备描述符(用于硬件输入)。在前面的代码中,调用 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();
}
但是,这不起作用。
最佳答案
您没有显示任何运行 io_service
的代码(run()
、poll()
、run_one()
或 poll_one()
)。所以什么也做不了。
这里是一个使用流描述符从/dev/inputN
读取的具体例子:
boost::asio read from /dev/input/event0
它只是使用 ::open
打开一个设备(在本例中为 /dev/input/event2
但它只是一个您可以更改的文件名)。
注意它是如何调用 io_service::run()
关于c++ - 用 boost::asio::io_service 替换 select(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46061972/