Keyboard device in Unix

一笑奈何 提交于 2019-12-07 12:16:21

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/15880196/keyboard-device-in-unix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!