引自:linux下C實現對鍵盤事件的監聽(按下鍵盤的時候程序立刻讀取)
- #include <termio.h>
- #include <stdio.h>
-
-
- int scanKeyboard()
- {
- int in;
- struct termios new_settings;
- struct termios stored_settings;
- tcgetattr(0,&stored_settings);
- new_settings = stored_settings;
- new_settings.c_lflag &= (~ICANON);
- new_settings.c_cc[VTIME] = 0;
- tcgetattr(0,&stored_settings);
- new_settings.c_cc[VMIN] = 1;
- tcsetattr(0,TCSANOW,&new_settings);
-
- in = getchar();
-
- tcsetattr(0,TCSANOW,&stored_settings);
- return in;
- }
-
- //這個方法就可以,返回值是該鍵的ASCII碼值,不需要回車的,
- //測試函數
- int main(){
- while(1){
- printf(":%d",scanKeyboard());
- }
- }
通過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循環讀取鍵盤效率很低,參考使用異步事件或者多線程技術。單線程爲阻塞式的