所需的代码相当复杂;我最终弄清楚了如何使用原始 ioctl、读取和写入来检查 C 中的 F1。如果您熟悉汇编和 Linux 系统调用,那么 nasm 的翻译应该很简单。
这并不完全是您想要的,因为它只检查 F1,而不检查其余的。 F1的序列是0x1b、0x4f、0x50。您可以使用以下命令找到其他序列od -t x1
并按下 键。例如,F2 为 0x1b、0x4f、0x51。
基本思想是,我们获取当前的终端属性,将它们更新为原始属性(cfmakeraw),然后将它们设置回来。 ioctl 系统调用用于此目的。
在处于原始模式的终端上,read()
将获取用户输入的任何字符,这与“cooked”模式不同,在“cooked”模式中,内核使用退格键和 control-u 进行行编辑,直到用户通过按 Enter 或 control-d (EOF) 提交该行。
#include <unistd.h>
#include <sys/ioctl.h>
#include <termios.h>
struct ktermios {
tcflag_t c_iflag;
tcflag_t c_oflag;
tcflag_t c_cflag;
tcflag_t c_lflag;
cc_t c_line;
cc_t c_cc[19];
};
int getch() {
unsigned char c;
read(0, &c, sizeof(c));
return c;
}
int main(int argc, char *argv[]) {
struct ktermios orig, new;
ioctl(0, TCGETS, &orig);
ioctl(0, TCGETS, &new); // or more simply new = orig;
// from cfmakeraw documentation
new.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
new.c_oflag &= ~OPOST;
new.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
new.c_cflag &= ~(CSIZE | PARENB);
new.c_cflag |= CS8;
ioctl(0, TCSETS, &new);
while (1) {
if (getch() == 0x1b && getch() == 0x4f && getch() == 0x50) {
break;
}
}
write(1, "Got F1!\n", 8);
ioctl(0, TCSETS, &orig); // restore original settings before exiting!
return 0;
}
我基于这个这个答案,这非常有帮助。