歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Unix知識 >> 關於Unix >> Linux下getch的模擬實現

Linux下getch的模擬實現

日期:2017/3/6 15:30:47   编辑:關於Unix
linux下默認是沒有提供getch這個函數的,我們這裡使用termios來模擬實現一個getch()函數,其基本原理為將終端設定為raw(或不緩沖的)模式。 int getch(void) struct termios tm, tm_old; int fd = S TD IN_FILENO, c; if(tcgetattr(fd, tm) 0) return -1; t

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;

 


Copyright © Linux教程網 All Rights Reserved