【发布时间】:2014-12-09 18:04:21
【问题描述】:
我编写了一个简单的 C 程序,它基本上由一个向上计数的无限循环组成。在循环过程中,会要求用户输入 - 而棘手的部分来了:在等待用户时不应该阻塞循环,而是在他输入时立即显示他的输入:
int main(void){
int i;
char dec;
for(;;i++){
printf("%d\n", i);
sleep(5);
if(i==4 || i==8){
printf("Please enter Y or N\n");
dec = fgetc(stdin);
printf("%c\n", dec);
}
}
return 0;
}
我在这里Python 找到了一个与 Python 类似的问题。那么我是否需要使用 pthread 将用户交互推送到新线程中,还是有更简单的选择?
谢谢!
编辑
int main(void){
int i=0;
char dec;
fd_set input_set;
for(;;i++){
printf("%d\n", i);
sleep(2);
if(i==4 || i==8){
FD_ZERO(&input_set ); /* Empty the FD Set */
FD_SET(0, &input_set); /* Listen to the input descriptor */
dec = select(1, &input_set, NULL, NULL, 0);
}
}
return 0;
}
【问题讨论】:
-
你使用什么操作系统?
标签: c loops pthreads block user-input