24

What I would like to take ownership of a hid device that may already have been plugged in, consume it's output, while preventing others(X11 or terminal) from consuming it.

If I can help it, I don't want to pretend to be a terminal, but rather to monopolize a particular hid or character device. The idea is that some hid devices may be recognized as mice/keyboards by x/terminal, but a second mouse or keyboard could be used for something else, but to do that you need to make sure they aren't sending spurious input into an open terminal.

Does anyone have any insight as to how this might be done?

1 Answer 1

26

I have done this - my specific application was a daemon that read events from a USB HID barcode reader (which presents as a USB HID keyboard device).

To do this I used the event device interface, opening the /dev/input/event* device corresponding to the device I was after. You can then issue the EVIOCGRAB ioctl on the device, which grabs it for exclusive use, and read events (which represent keypresses, mouse movements etc) from the device as they become available.

(When the device is grabbed for exclusive use, only your application will see events from it).

11
  • 2
    Sounds just what I need for a RFID reader that reads a 10-digit number from a tag and presents the information as a keyboard input so as to use as an access control device in conjunction with a Raspberry Pi Home-automation project - and still be able to log in with a keyboard/mouse/monitor for other (debugging) purposes.
    – SlySven
    Commented Jan 10, 2016 at 3:15
  • Sometimes I wonder if stackexchange was sent on Earth to save us all ! Is your project Open source ? Do you mind sharing the sources ? I'love to control a few things using custom printed QR-codes.
    – Michel L
    Commented Jan 12, 2017 at 22:49
  • @SlySven Is your project Open source too ? Do you mind sharing the sources ?
    – Michel L
    Commented Jan 12, 2017 at 22:49
  • @MichelL: I'll see if I can dig up the code but it's nothing super complicated.
    – caf
    Commented Jan 13, 2017 at 1:00
  • 1
    @MichelL - it is still incomplete but eventually I'll try to make it available in my GitHub repositories - but it will be GPLed 2+ so I don't want to post it here as I've not got to the bottom of exact terms for stuff published here! Basically use int fd= open( devPathFile", O_RDWR|O_NONBLOCK, S_IRUSR|S_IWUSR ) to open the device and get the file descriptor number fd, then use ioctl( fd, EVIOCGRAB, 1 ) to grab exclusive use. Don't forget to handle the signals that will close your program so that you can release that exclusivity (though it might happen automatically on application...
    – SlySven
    Commented Jan 13, 2017 at 21:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.