Username: Password:

Linux下getch的模拟实现
来源:Blog.ChinaUnix.net作者:Blog.ChinaUnix.net 发布时间:2008-04-07 03:49:49

linux下默认是没有提供getch这个函数的,我们这里使用termios来模拟实现一个getch()函数,其基本原理为将终端设定为raw(或不缓冲的)模式。

 int getch(void) 
{
struct termios tm, tm_old;
int fd = STDIN_FILENO, c;

if(tcgetattr(fd, &tm) < 0)
return -1;

tm_old = tm;

cfmakeraw(&tm);

if(tcsetattr(fd, TCSANOW, &tm) < 0)
return -1;

c = fgetc(stdin);

if(tcsetattr(fd, TCSANOW, &tm_old) < 0)
return -1;

return c;
}

这里的getch()实际相当于turbo c中的kbhit(), 其中关键为cfmakeraw对终端的相关控制

,man page 说明cfmakeraw()实际上做了:


cfmakeraw sets the terminal attributes as follows:
termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
|INLCR|IGNCR|ICRNL|IXON);
termios_p->c_oflag &= ~OPOST;
termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
termios_p->c_cflag &= ~(CSIZE|PARENB);
termios_p->c_cflag |= CS8;

 


喜欢本文,那就收藏到:

    Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪ViVi 365Key网摘 天极网摘 和讯网摘 博拉网 POCO网摘 添加到饭否 QQ书签 Digbuzz我挖网
相关评论  我也要评论
还没有关于此文章的相关评论!
  • 昵称: (为空则显示guest)
  • 评论分数: ★ ★ ★★★ ★★★★ ★★★★★
  • 评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
  • 导航
    赞助商
    文章类别
    订阅