Question

I have been thinking a lot over keyboard handling. How does it work? I can't seem to google me to a good explaining.

I know that a keyboard interrupt is made every time a key is pressed. The processor halts whatever it is processing and load the keyboard data from the keyboard buffer, storing it in a system level buffer.

But what happens next? Let's take a practical example. What happens when I run the following piece of code:

...
std::string s;
std::cin >> s;
....

Does the cin read from a user level representation of the system level keyboard buffer? That makes perfect sense in my head because then 2, or more processes can read from the same buffer, and by that way I don't loose any key presses. But does it work this way?

I know I'm talking in very general terms. The OS I'm using is OS X.

Was it helpful?

Solution

Except in rare situations, your keyboard and display are managed by a Window Manager: X11, Gnome, KDE, Carbon, Cocoa or Windows.

It works like this.

The keyboard driver is part of the OS.

The window manager is a privileged process, which acquires the device during startup. The window manager "owns" the device. Exclusively.

  1. The interrupts go to OS.

  2. The OS responds the interrupt by queueing. Eventually -- when there's nothing of a higher priority to do -- it captures the keyboard input from the interrupt and buffers it.

  3. The owning process (the window manager) is reading this buffer. From this, it creates keyboard events.

Your application works through the window manager.

Example 1 -- You're running a command-line application. In a terminal window. When terminal window is front-most, the window manager directs events at the terminal window. Keyboard events become the stdin stream.

Example 2 -- you're running GUI application. In your own application's window. When your application's window is front-most, the window manager direct events at your application window. Keyboard events are available for your various GUI controls to process. Some keyboard events may cycle among the controls or active buttons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top