Issue
I'd like capture all user input, reading one byte at a time, from a keyboard device. I've written the following piece of code but it's not working:
if ((fd = open("/dev/char", O_RDONLY) != 1) {
tty = open("/dev/tty", O_RDONLY);
tcsetattr(0, TCSANOW, &orig_info);
read (fd, &buf, sizeof(char));
}
close(fd);
I expected the terminal to wait for input, but it didn't.
Solution
The keyboard device itself is one of the entries in /dev/input
. You can locate keyboards and other input devices by their connection type (e.g. PS/2, USB, …) in /dev/input/by-path
. Obviously, you'll need to run as root to access the hardware directly, and you'll need to provide your own translation from raw bytes coming from the keyboard into things like key presses and key releases. This is probably not what you want.
If you're running a GUI application, the low-level method is to call XNextEvent
and other functions in the same family. Decoding input events isn't completely trivial, as it's up to applications to apply modifiers. A GUI framework (Motif, Gtk, Qt, …) would help you.
If you're running a terminal application, read from standard input or from /dev/tty
(/dev/tty
is always the terminal that your program is running on, even if standard input has been redirected). You'll want to put the terminal in raw mode. You'll get decoded character keys, and function keys mostly as escape sequences. Here, too, a library helps; the de facto standard is ncurses.
Answered By - Gilles 'SO- stop being evil' Answer Checked By - Timothy Miller (WPSolving Admin)