Search code examples
linuxoperating-systemkeyboardlinux-device-driver

How does OS know to which process send a keyboard interrupt?


Below is a simple c program (for Ubuntu OS) that waits for any keyboard key to be pressed and then terminates.

#include <cstdio>
#include <conio.h>

int main() {
    while(true) {
        if (_kbhit()) {
            printf("Key hit\n");
            return 0;
        }
    }
    return 0;
}

If I start this program on a terminal nr. 1, the program reacts to me pressing the keys only if the mouse is pointing to a terminal 1. Thus, if two such programs are running as separate processes at the same time, pressing a key will terminate at most one program.

How does the OS know to which process send a keyboard interrupt?


Solution

  • Big question. In your example, as stated it doesn't; depending upon your definition of OS.

    In a classic unix system, the GUI is provided by a relatively conventional program running in user space. The GUI (eg. X11) is the only one connected to the actual keyboard device; and it translates those keys into events in the GUI. When a key is pressed, whichever window in the GUI that has input focus will receive the event.

    A terminal emulator is a program which runs within the GUI, providing programs with a 1970s tty interface to the GUI. This program utilizes a special type of tty-device, called a pseudo-tty, which functions very much like a pipe(2) that supports the terminal specific functions (tc*, ioctl). When the terminal emulator receives a GUI event indicating a key hit, it injects it into the pseudo-tty, which then provides it to the program as an ascii/utf-8 character.

    The GUI chooses which window has focus for input events by configuration. Some people prefer geographic -- which ever window the mouse pointer is in receives these events; some prefer click to focus, where you must click in a window to determine who has focus. Both have advantages and disadvantages; but if you often receive strange messages in irc/slack/... from somebody, they likely chose click-to-focus.

    In the absence of a gui, the answer is both easier and more intricate. In the obvious case, it is the program printing the "$ " prompt at you; in the intricate case, you need to read up on sessions, process groups, controlling terminals, job control.