歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux使用static關鍵字保存和恢復程序運行狀態

Linux使用static關鍵字保存和恢復程序運行狀態

日期:2017/2/28 16:06:36   编辑:Linux教程
做了一個控制Linux終端狀態的實驗,程序運行過程中,終端需要調整到 nobuffer、noecho。即,無緩沖,無回顯狀態。並且一次僅能接受一個字符的輸入。

實現如下:

  1. int set_cr_noecho_mode()
  2. {
  3. struct termios ttystate;
  4. tcgetattr(0, &ttystate); // read current setting
  5. ttystate.c_lflag &= ~ICANON; //no buffering
  6. ttystate.c_lflag &= ~ECHO; //no echo
  7. ttystate.c_cc[VMIN] = 1; // get 1 char at a time
  8. tcsetattr(0, TCSANOW, &ttystate); // install setting
  9. }
為了在這些設置使用過後,能恢復終端在次之前的狀態,必須對其狀態進行保存,使用一個static變量就可以輕松解決!這個方法,同樣適用於很多臨時改變狀態,並且需要恢復的情況。
  1. </pre><pre name="code" class="html">int tty_mode(int how)
  2. {
  3. static struct termios original_mode;
  4. static int original_flags;
  5. if(how == 0)
  6. {
  7. //save
  8. tcgetaddr(0, &original_mode);
  9. original_flags = fcntl(0, F_GETFL);
  10. }
  11. else
  12. {
  13. //restore
  14. tcsetattr(0, TCSANOW, &original_mode);
  15. fcntl(0, F_SETFL, original_flags);
  16. }
  17. }
Copyright © Linux教程網 All Rights Reserved