做了一個控制Linux終端狀態的實驗,程序運行過程中,終端需要調整到 nobuffer、noecho。即,無緩沖,無回顯狀態。並且一次僅能接受一個字符的輸入。
實現如下:
- int set_cr_noecho_mode()
- {
- struct termios ttystate;
- tcgetattr(0, &ttystate); // read current setting
- ttystate.c_lflag &= ~ICANON; //no buffering
- ttystate.c_lflag &= ~ECHO; //no echo
- ttystate.c_cc[VMIN] = 1; // get 1 char at a time
- tcsetattr(0, TCSANOW, &ttystate); // install setting
- }
為了在這些設置使用過後,能恢復終端在次之前的狀態,必須對其狀態進行保存,使用一個static變量就可以輕松解決!這個方法,同樣適用於很多臨時改變狀態,並且需要恢復的情況。
- </pre><pre name="code" class="html">int tty_mode(int how)
- {
- static struct termios original_mode;
- static int original_flags;
-
- if(how == 0)
- {
- //save
- tcgetaddr(0, &original_mode);
- original_flags = fcntl(0, F_GETFL);
- }
- else
- {
- //restore
- tcsetattr(0, TCSANOW, &original_mode);
- fcntl(0, F_SETFL, original_flags);
- }
- }