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循環讀取鍵盤效率很低,參考使用異步事件或者多線程技術。單線程爲阻塞式的




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