linux记录键盘
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<termios.h> 5 #include<term.h> 6 #include<curses.h> 7 #include<unistd.h> 8 static struct termios initial_settings,new_settings; 9 static int peek_character=-1; 10 void init_keyboard(); 11 void close_keyboard(); 12 int check_keyboard(); 13 int readch(); 14 int main() 15 { 16 int ch=0; 17 init_keyboard(); 18 while(ch!=‘q‘) 19 { 20 printf("looping\n"); 21 sleep(1); 22 if(check_keyboard()) 23 { 24 ch=readch(); 25 /// scanf("%c",&ch); 26 printf("You hit %c\n",ch); 27 } 28 } 29 close_keyboard(); 30 exit(0); 31 } 32 33 int readch() 34 { 35 char ch; 36 if(peek_character!=-1) 37 { 38 ch=peek_character; 39 peek_character=-1; 40 return ch; 41 } 42 read(0,&ch,1); 43 return ch; 44 } 45 46 void init_keyboard() 47 { 48 tcgetattr(0,&initial_settings); 49 new_settings=initial_settings; 50 new_settings.c_lflag &=~ICANON; 51 new_settings.c_lflag &=~ECHO; 52 new_settings.c_lflag &=~ISIG; 53 new_settings.c_cc[VTIME]=0; 54 new_settings.c_cc[VMIN]=1; 55 tcsetattr(0,TCSANOW,&new_settings); 56 } 57 58 void close_keyboard() 59 { 60 tcsetattr(0,TCSANOW,&initial_settings); 61 } 62 63 int check_keyboard() 64 { 65 char ch; 66 int nread; 67 if(peek_character!=-1) 68 { 69 return 1; 70 } 71 new_settings.c_cc[VMIN]=0; 72 tcsetattr(0,TCSANOW,&new_settings); 73 nread=read(0,&ch,1); 74 new_settings.c_cc[VMIN]=1; 75 tcsetattr(0,TCSANOW,&new_settings); 76 if(nread==1) 77 { 78 peek_character=ch; 79 return 1; 80 } 81 return 0; 82 }
如图所示,按q退出
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。