I am using the gpio-keys device driver to handle some buttons in an embedded device running Linux. Applications in user space can just open /dev/input/eventX
and read input events in a loop.
My question is how to get the initial states of the buttons. There is an ioctl call (EVIOCGKEY
) which can be used for this, however if I first check this and then start to read from /dev/input/eventX
, there's no way to guarantee that the state did not change in between.
Any suggestions?
The evdev devices queue events until you
read()
them, so in most cases opening the device, doing theioctl()
and immediately starting to read events from it should work. If the driver dropped some events from the queue, it sends you aSYN_DROPPED
event, so you can detect situations where that happened. The libevdev documentation has some ideas on how one should handle that situation; the way I read it you should simply retry, i.e. drop all pending events, and redo theioctl()
until there are no moreSYN_DROPPED
events.I used this code to verify that this approach works:
After starting, the program deliberately waits 5 seconds. Hit some keys in that time to fill the buffer. On my system, I need to enter about 70 characters to trigger a
SYN_DROPPED
. TheEV_KEY
handling code checks if the events are consistent with the state reported by theEVIOCGKEY
ioctl.