我一直在学习守护进程并用C编写它们。我想让守护进程接收Ubuntu中的全局按键信号,并将接收到的按键信号写入一个单独的文件。
有什么办法可以实现吗?如果是这样,怎么办?
答案1
最直接的方法是读取暴露的事件设备/dev/input/
.读内核文档Linux 输入子系统,从中您可以学习如何用 C 操作这些设备。
有几个软件包可供您快速测试您的输入设备。例如,您可以apt-get install input-utils
在 Ubuntu 上使用以下工具。
lsinput
:枚举连接到系统的输入设备。
$ sudo lsinput
/dev/input/event0
bustype : BUS_HOST
vendor : 0x0
product : 0x3
version : 0
name : "Sleep Button"
phys : "PNP0C0E/button/input0"
bits ev : EV_SYN EV_KEY
/dev/input/event1
bustype : BUS_HOST
vendor : 0x0
product : 0x5
version : 0
name : "Lid Switch"
phys : "PNP0C0D/button/input0"
bits ev : EV_SYN EV_SW
/dev/input/event2
bustype : BUS_HOST
vendor : 0x0
product : 0x1
version : 0
name : "Power Button"
phys : "LNXPWRBN/button/input0"
bits ev : EV_SYN EV_KEY
/dev/input/event3
bustype : BUS_I8042
vendor : 0x1
product : 0x1
version : 43841
name : "AT Translated Set 2 keyboard"
phys : "isa0060/serio0/input0"
bits ev : EV_SYN EV_KEY EV_MSC EV_LED EV_REP
这/dev/input/event3
是您可能想要观看的键盘设备。
input-events
:读取并显示来自输入设备的事件。它需要一个设备号参数,例如3
for /dev/input/event3
。
$ sudo input-events 3
/dev/input/event3
bustype : BUS_I8042
vendor : 0x1
product : 0x1
version : 43841
name : "AT Translated Set 2 keyboard"
phys : "isa0060/serio0/input0"
bits ev : EV_SYN EV_KEY EV_MSC EV_LED EV_REP
waiting for events
09:27:02.961576: EV_MSC MSC_SCAN 50
09:27:02.961576: EV_KEY KEY_M (0x32) released
09:27:02.961576: EV_SYN code=0 value=0
09:27:03.833925: EV_MSC MSC_SCAN 58
09:27:03.833925: EV_KEY KEY_CAPSLOCK (0x3a) released
09:27:03.833925: EV_SYN code=0 value=0
09:27:09.344765: EV_MSC MSC_SCAN 30
09:27:09.344765: EV_KEY KEY_A (0x1e) pressed
09:27:09.344765: EV_SYN code=0 value=0
09:27:09.446881: EV_MSC MSC_SCAN 30
09:27:09.446881: EV_KEY KEY_A (0x1e) released
09:27:09.446881: EV_SYN code=0 value=0
09:27:09.548389: EV_MSC MSC_SCAN 48
09:27:09.548389: EV_KEY KEY_B (0x30) pressed
09:27:09.548389: EV_SYN code=0 value=0
09:27:09.640385: EV_MSC MSC_SCAN 48
09:27:09.640385: EV_KEY KEY_B (0x30) released
09:27:09.640385: EV_SYN code=0 value=0
09:27:09.781365: EV_MSC MSC_SCAN 46
09:27:09.781365: EV_KEY KEY_C (0x2e) pressed
09:27:09.781365: EV_SYN code=0 value=0
09:27:09.853143: EV_MSC MSC_SCAN 46
09:27:09.853143: EV_KEY KEY_C (0x2e) released
09:27:09.853143: EV_SYN code=0 value=0
...