Linux 监测键盘输入

原文链接:https://blog.csdn.net/u013467442/article/details/51173441

引自:linux下C实现对键盘事件的监听(按下键盘的时候程序立刻读取)


  1. #include <termio.h>
  2. #include <stdio.h>
  3. int scanKeyboard()
  4. {
  5. int in;
  6. struct termios new_settings;
  7. struct termios stored_settings;
  8. tcgetattr(0,&stored_settings);
  9. new_settings = stored_settings;
  10. new_settings.c_lflag &= (~ICANON);
  11. new_settings.c_cc[VTIME] = 0;
  12. tcgetattr(0,&stored_settings);
  13. new_settings.c_cc[VMIN] = 1;
  14. tcsetattr(0,TCSANOW,&new_settings);
  15. in = getchar();
  16. tcsetattr(0,TCSANOW,&stored_settings);
  17. return in;
  18. }
  19. //这个方法就可以,返回值是该键的ASCII码值,不需要回车的,

  1. //测试函数
  2. int main(){
  3. while(1){
  4. printf(":%d",scanKeyboard());
  5. }
  6. }

通过tcsetattr函数设置terminal的属性来控制需不需要回车来结束输入。

更详细的参考 man 3 tcgetattr

ICANON
Enable canonical mode. This enables the special characters EOF, EOL, EOL2, ERASE, KILL, LNEXT, REPRINT, STATUS, and WERASE, and buffers by lines.

可以看出ICNAON标志位启用了整行缓存。

所以,new_settings.c_lflag &= (~ICANON);这句屏蔽整行缓存。那就只能单个了。


另外一个可运行的例子:http://blog.csdn.net/alangdangjia/article/details/27697721


注:通过while循环读取键盘效率很低,参考使用异步事件或者多线程技术。单线程为阻塞式的




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章