1. 通过 fcntl 函数改变标准输入的 read 模式为非阻塞状态,这样当我们读取键盘字符时就可以非阻塞程序。
#include <fcntl.h>
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
2. 编写检测键盘事件程序(转载自:http://blog.csdn.net/alangdangjia/article/details/27697721)
#include <termios.h>
#include <fcntl.h>
static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard(void);
void close_keyboard(void);
int kbhit(void);
int readch(void);
void init_keyboard()
{
tcgetattr(0,&initial_settings);
new_settings = initial_settings;
new_settings.c_lflag |= ICANON;
new_settings.c_lflag |= ECHO;
new_settings.c_lflag |= ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
}
void close_keyboard()
{
tcsetattr(0, TCSANOW, &initial_settings);
}
int kbhit()
{
unsigned char ch;
int nread;
if (peek_character != -1) return 1;
new_settings.c_cc[VMIN]=0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0,&ch,1); //非阻塞读取stdin一个字符
new_settings.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new_settings);
if(nread == 1)
{
peek_character = ch;
return 1;
}
return 0;
}
int readch()
{
char ch;
if(peek_character != -1)
{
ch = peek_character;
peek_character = -1;
return ch;
}
read(0,&ch,1);
return ch;
}
main程序:
int mian()
{
init_keyboard();
while (true) {
kbhit();
int ret_read = readch();
if(ret_read == 10) //当遇到ENTER按下事件退出监测
{
break;
}
}
close_keyboard();
}