作者:wo缘相聚在空间 | 来源:互联网 | 2022-12-02 17:58
1> David Collin..:
以下简短程序既不需要ncurses也不需要线程.但是,它确实需要更改终端属性 - 使用tcsetattr()
.这适用于Linux和类Unix系统,但不适用于Windows - 不包括termios.h
头文件.(如果您对该主题感兴趣,也许可以看这篇文章.)
#include
#include
#include
int main(int argc, char *argv[]) {
struct termios orig_attr, new_attr;
int c = '\0';
// or int n = atoi(argv[1]);
int n = 5;
tcgetattr(fileno(stdin), &orig_attr);
memcpy(&new_attr, &orig_attr, sizeof(new_attr));
new_attr.c_lflag &= ~(ICANON | ECHO);
new_attr.c_cc[VMIN] = 0;
// Wait up to 10 deciseconds (i.e. 1 second)
new_attr.c_cc[VTIME] = 10;
tcsetattr(fileno(stdin), TCSANOW, &new_attr);
printf("Starting with n = %d\n", n);
do {
c = getchar();
if (c != EOF) {
n++;
printf("Key pressed!\n");
printf("n++ => %d\n", n);
} else {
n--;
printf("n-- => %d\n", n);
if (n == 0) {
printf("Exiting ...\n");
break;
}
if (feof(stdin)) {
//puts("\t(clearing terminal error)");
clearerr(stdin);
}
}
} while (c != 'q');
tcsetattr(fileno(stdin), TCSANOW, &orig_attr);
return 0;
}
关键点是
new_attr.c_lflag &= ~(ICANON | ECHO);
使终端退出规范模式(并禁用字符'echo'),
new_attr.c_cc[VMIN] = 0;
将它置于轮询(而不是"阻塞")模式,和
new_attr.c_cc[VTIME] = 10;
指示程序等待直到输入10个十分.
更新(2019-01-13)
添加clearerr(stdin)
清除(在某些平台EOF
上stdin
似乎是必要的)