文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Linux下getch的模拟实现

Linux下getch的模拟实现

时间:2005-08-03  来源:new_cooperator

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;

 


相关阅读 更多 +
排行榜 更多 +
弓箭手战士酷跑

弓箭手战士酷跑

飞行射击 下载
三角洲行动全面战场攀升A点进攻指南

三角洲行动全面战场攀升A点进攻指南

飞行射击 下载
僵尸射手世界大战

僵尸射手世界大战

飞行射击 下载