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

来源:互联网 发布:移动免流端口 编辑:程序博客网 时间:2024/06/05 10:26

今天做了一个控制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变量就可以轻松解决!这个方法,同样适用于很多临时改变状态,并且需要恢复的情况。

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);    }}



原创粉丝点击