在没有 X Window 的情况下用 C 捕获 GNU/Linux 中的击键
如果我正在一个应用程序中工作,并且从键盘上按下一个键,那么如何在没有 X Window 的情况下捕获该键(或字符串),包括 C 语言、GNU/LINUX 下、用户空间中的源应用程序名称?
If I am working in an application and I press a key from the keyboard, how can I capture that key (or string), including the source application's name, in C, under GNU/LINUX, in userland, without X Window?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,如果没有 X Window,这个问题就会变得更加困难。
对于击键部分,您可以使用与此类似的代码,但是您必须将设备作为您正在读取的参数传递(键盘,通常是 /dev/input/event0
)大部头书。此代码取自 Ventriloctrl hack,用于获取击键 - http: //public.callutheran.edu/~abarker/ventriloctrl-0.4.tar.gz。
Well, without X Window this problem is way more difficult.
For the keystroke part, you can use code similar to this one, but you have to pass the device as an argument that you are reading (keyboard, usually /dev/input/event0)
Credits do not go to me. This code is taken from the Ventriloctrl hack to get keystrokes - http://public.callutheran.edu/~abarker/ventriloctrl-0.4.tar.gz.
您可以从 /dev/input 中的文件之一读取数据。哪一个取决于您的系统。它可能是 /dev/input/event0 或 /dev/input/by-path/platform-i8042-serio-0-event-kbd 或其他东西。格式在内核头文件 input.h 中指定。您
可以运行
并输入一些内容来看看会发生什么。
至于找出哪个应用程序收到了关键事件,我不确定。您可以尝试检查哪一个正在从主 tty 读取。
You can read data from one of the files in /dev/input. Which one depends on your system. It might be /dev/input/event0 or /dev/input/by-path/platform-i8042-serio-0-event-kbd or something else. The format is specified in the kernel header input.h. It is
You can run
and type something to see what happens.
As for finding out which application received the key event, I'm not sure. You could try checking which one is reading from the main tty.
要获得一个很好的示例,请查看 showkey 的代码。
特别是,这是主循环。它所做的就是获取终端,复制它,将复制的终端转换为原始模式,直到给出“退出”或“中断”键序列为止,它仅打印出向终端提供的键。
For a pretty good example, have a look at showkey's code.
In particular, here's the main loop. All it does is get the terminal, copy it, turn the copied one to raw mode, and until a 'quit' or 'interrupt' key sequence is given, it merely prints out what key was given to the terminal.
一种可能性:找到并查看“sudosh”(“sudo shell”)的源代码(或者它的替代品之一,因为它已经有一段时间没有修改了;谷歌是你的朋友)。
它与伪终端混淆并通过将信息记录到文件来跟踪所有输入和输出。
这对你来说是否足够精确可能还有待商榷。它会记录所有应用程序的所有击键。我也不确定它如何与 X11 一起工作 - 如果它与 X11 一起工作。
One possibility: find and take a look at the source for 'sudosh', the 'sudo shell' (or one of its replacements since that has not been modified in a while; Google is your friend).
It messes with pseudo-ttys and tracks all the input and output by also recording the information to file.
Whether that is precise enough for you is perhaps more debatable; it would log all keystrokes for all applications. I'm also not certain how it works with X11 - if it works with X11.