2

I am trying to replace the main loop in my program ( while(1)...select() ) with boost::asio::io_service.run(). The program has a couple sockets open, which were monitored by select().

The tricky part is that the FD_SET in the select statement has socket file descriptors as well as char device descriptors (for hardware input). In the previous code, calling int fd = open("/dev/button1", O_RDONLY); was enough, and that fd was added to the FD_SET. The select() statement is able to monitor all of them.

So in order to be able to monitor the character device from boost::asio::io_service, I've been reading a lot about boost::asio::stream_descriptor. But I haven't been able to get it to work.

I've tried opening the device normally and then creating a stream_descriptor, and adding it to the 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();
}

However, that does not work.

Rusty
  • 1,095
  • 9
  • 15
  • Did you consider using [poll(2)](http://man7.org/linux/man-pages/man2/poll.2.html) instead of `select` ? – Basile Starynkevitch Sep 05 '17 at 19:24
  • Does `btn` maybe get out-of-scope directly before async_read really does it's job (when the io_service is run) and therefore it gets destructed and the callback never called? We can only guess, the shown code looks ok, the error is likely somewhere else. – Matthias247 Sep 06 '17 at 00:17

1 Answers1

1

You don't show any code that runs the io_service (run(), poll(), run_one() or poll_one()). So nothing gets done.

A specific example that uses stream-descriptor to read from /dev/inputN is here:

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

It just uses ::open to open a device (in this case, /dev/input/event2 but it's just a filename you can change).

Note how it calls io_service::run()

sehe
  • 374,641
  • 47
  • 450
  • 633