我需要知道在Linux中哪个中断会检查是否有按键被按下?
我需要知道在Linux中哪个中断会检查是否有按键被按下?
termios(3)
函数控制。 Linux最终将它们转换为ioctl()调用,如下所示(请参见
termios(3)
和poll(2)
执行您要求的操作的C程序(出于简洁和清晰的原因省略了错误检查):#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>
#include <signal.h>
#include <termios.h>
#include <sys/ioctl.h>
static sig_atomic_t end = 0;
static void sighandler(int signo)
{
end = 1;
}
int main()
{
struct termios oldtio, curtio;
struct sigaction sa;
/* Save stdin terminal attributes */
tcgetattr(0, &oldtio);
/* Make sure we exit cleanly */
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sighandler;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
/* This is needed to be able to tcsetattr() after a hangup (Ctrl-C)
* see tcsetattr() on POSIX
*/
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = SIG_IGN;
sigaction(SIGTTOU, &sa, NULL);
/* Set non-canonical no-echo for stdin */
tcgetattr(0, &curtio);
curtio.c_lflag &= ~(ICANON | ECHO);
tcsetattr(0, TCSANOW, &curtio);
/* main loop */
while (!end) {
struct pollfd pfds[1];
int ret;
char c;
/* See if there is data available */
pfds[0].fd = 0;
pfds[0].events = POLLIN;
ret = poll(pfds, 1, 0);
/* Consume data */
if (ret > 0) {
printf("Data available\n");
read(0, &c, 1);
}
}
/* restore terminal attributes */
tcsetattr(0, TCSANOW, &oldtio);
return 0;
}
ioctl
和poll
都是系统调用,在/usr/include/asm/unistd.h中可以找到它们的编号(在x86上为54和168),而/usr/include/asm/ioctls.h则包含了你需要的ioctl常量(在x86上为TCGETS=0x5401、TCSETS=0x5402、TCSETSW=0x5403、TCSETSF=0x5404)。