Linux使用static关键字保存和恢复程序运行状态


做了一个控制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.    
  6.     if(how == 0)  
  7.     {  
  8.         //save   
  9.         tcgetaddr(0, &original_mode);        
  10.         original_flags = fcntl(0, F_GETFL);  
  11.      }  
  12.     else  
  13.     {  
  14.        //restore   
  15.         tcsetattr(0, TCSANOW, &original_mode);  
  16.         fcntl(0, F_SETFL, original_flags);  
  17.     }  
  18. }  

相关内容