1、利用Input子系统来获取信息
通过如下命令获取键盘对应的event id
cat /proc/bus/input/devices
我的电脑对应的是event4,实现代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <linux/input.h>
#define INPUT_KEYBOARD "/dev/input/event4"
int get_key_board_from_input()
{
int fd = -1, ret = -1;
struct input_event ev;
fd = open(INPUT_KEYBOARD , O_RDONLY);
if(fd < 0) {
printf("open failed, error:%d\n", errno);
return -1;
}
while(1) {
memset(&ev, 0, sizeof(struct input_event));
ret = read(fd, &ev, sizeof(struct input_event));
if (ret != sizeof(struct input_event)) {
printf("read error, ret: %d\n", ret);
break;
}
if (ev.type == EV_KEY) {
printf("--------------------\n");
printf("type = %u.\n", ev.type); /* 消息类型,EV_KEY是按键 */
printf("code = %u.\n", ev.code); /* 按键信息,/usr/include/linux/input-event-codes.h文件中有定义键值,例如KEY_ESC对应esc按键 */
printf("value = %u.\n", ev.value); /* 按键是按下还是释放,0释放、1按下、2长按 */
}
}
close(fd);
return ret;
}
这个方法能很全面的获取按键的信息,但是不便的是需要root权限来运行
2、通过更改控制台设置,获取键盘值ASCII码
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
int get_key_board_from_termios()
{
int key_value;
struct termios new_config;
struct termios old_config;
tcgetattr(0, &old_config);
new_config = old_config;
new_config.c_lflag &= ~(ICANON | ECHO);
tcsetattr(0, TCSANOW, &new_config);
key_value = getchar();
tcsetattr(0, TCSANOW, &old_config);
printf("key_value: %d\n", key_value);
return 0;
}
无需root权限即可执行