您的位置:首页 > 其它

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

2011-09-18 11:55 232 查看
今天做了一个控制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);
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐