I am making a Ruby program so I can play different sounds when a key is pressed. Key A will make different sound from key S and so on. I want to get raw inputs rather than using some ruby gems.

For example I can read /dev/input/mice for all mice events. I can use it in my code so that it can do some job based on the mouse movements.

By opening which file can I grab all the keyboards' events?

1 Answer 1


There are two layers involved here: The input layer of the kernel, which translates various keyboard, mice, joysticks etc. into a common framework, and makes them available on /dev/input/* device files (one file per device), and the X (or, depending on your distro, Wayland) layer, which reads those files, and translates them into X events which are understood by graphical applications. The latter combines the input devices and makes them available as "keyboard events from any device" and "mouse events from any device" (this is a simplification, but ok is first aproximation).

The natural way for an application is to interact with the X layer (and I'm sure there as a Ruby abstraction for that). This is in particular recommended if your application not only plays sounds, but also displays something (and even if it doesn't display anything).

Of course, if you insist, you can also open all files in /dev/input/*, and interpret the events coming from them, but this will fail the moment a new keyboard a mouse gets attached, and you want to react on those events, too.

The /dev/input/mice abstraction only exists for mice, and is a sort of legacy solution invented at the time when people were using a single PS/2 keyboard, but there were already all kinds of different mouse devices. This file may not match what the X layer considers active mouse input devices, and there's no equivalent abstraction for keyboards.

  • So I was looking at a keylogger for Ruby: <github.com/maltoe/ruby-keylogger> Seems like the developer has included the input.h header file in his C code, then the Ruby code uses the compiled C code (which is obvious for most of the gems)...
    – 15 Volts
    Apr 22, 2019 at 6:29
  • 1
    And note the description: " tries to listen to the first keyboard input device found in /dev/input/by-id" (my emphasis). The format for the events is very simple, I'm sure you can parse it directly in Ruby (I've done it in Perl with pack/unpack). I'd still recommend the X layer, though; googling "ruby xinput" turns up quite a few hits.
    – dirkt
    Apr 22, 2019 at 7:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .