#include <termios.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
char c;
struct termios tTTYState;
//get the terminal state
tcgetattr(STDIN_FILENO, &tTTYState);
//turn off canonical mode
tTTYState.c_lflag &= ~ICANON;
//minimum of number input read.
tTTYState.c_cc[VMIN] = 1; /* 有一个数据时就立刻返回 */
//set the terminal attributes.
tcsetattr(STDIN_FILENO, TCSANOW, &tTTYState);
while (1)
{
c = fgetc(stdin); /* 会休眠直到有输入 */
printf("get char : %c\n", c);
}
return 0;
}
本文介绍了一个使用C语言实现的非阻塞字符读取程序。该程序通过修改终端属性来禁用规范模式,并设置最小读取字符数为1,从而实现字符的即时读取而无需按下回车键。代码展示了如何获取当前终端状态、更改设置并最终恢复默认配置的过程。





