重點如下:
1.不需要管理員權限
讀取/dev/input/event1需要root權限,改用讀取/dev/tty的方法
要說明的是/dev/tty不是一個真實的終端,而是一個軟鏈接,對應到當前shell的tty。
2.不回顯(通過設置~ECHO)
3.非阻塞(不需要回車,設置O_NONBLOCK)
4.程序結束後恢復原始設置(包括正常退出和異常退出)
代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input.h>
#include <termios.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <sys/types.h>
#include <signal.h>
static int tty_fd = -1;
static struct termios save_tty,save_stdin,nt;
int main(int argc,char*argv[])
{
int tty_fd=open("/dev/tty",O_RDONLY);
char temp;
tcgetattr(0,&save_stdin);
nt=save_stdin;
nt.c_lflag &= ~(ECHO|ICANON);//設爲0所以用&
tcsetattr(0,TCSANOW,&nt);
int flags = fcntl(tty_fd,F_GETFL);
flags |= O_NONBLOCK;//設爲1所以用|
if(fcntl(tty_fd,F_SETFL,flags)==-1){exit(1);}
flags = fcntl(0,F_GETFL);
//flags |= O_NONBLOCK;
if(fcntl(0,F_SETFL,flags)==-1){exit(1);}
while(1)
{
read(tty_fd,&temp,1);
switch(temp)//檢測按下了什麼鍵
{
case 'w':
{
printf("you press w \n");
}break;
case 's':
{
tcsetattr(0,TCSANOW,&save_stdin);
close(tty_fd);
return 0;
}break;
default:;
}
}
return 0;
}