سؤال

How to capture all the user input, reading one byte at a time?

I did this coding, 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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

What exactly do you want to do?

If what you are looking for is unbuffered input in terminal, tcsetattr() is what you are looking for - you need to put the terminal into the non-canonical mode, i.e. set the terminal flags not to contain ICANON - see e.g. this code snippet. See man termios (or the function name, it usually links to the same man page on Linux).

If you want to have exclusive access to the keyboard, it is much more complicated.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top