所以我做了这个函数,它的作用就像倒计时。我想在倒计时减少时读取命令。我的大问题是在倒计时减少时等待输入。正如你所看到的,我尝试使用
read()
但在第一个 select()
之后它停止尝试读取。我只表演了一次printf("timeout.\n");
否则就会一直到倒计时达到0。我需要尝试再次阅读。timeout
编辑:要使用
int timer(int seconds)
{
time_t start, end;
double elapsed;
int opened=0;
char command[10];
struct timeval tv;
int fd_stdin,rv;
fd_set rd;
fd_stdin=fileno(stdin);
FD_ZERO(&rd);
FD_SET(fileno(stdin),&rd);
tv.tv_sec=5;
tv.tv_usec=0;
time(&start); /* start the timer */
do
{
time(&end);
elapsed = difftime(end, start);
if(fmod(elapsed,5)==0)
{
printf("Time remaining: %f minutes.\n", (seconds-elapsed)/60);
sleep(1);
if(opened==0)
{
printf("Use opentest to open your test.\n");
opened=1;
}
fflush(stdout);
}
int c;
rv=select(fd_stdin+1,&rd,NULL,NULL,&tv);
if(rv==-1)
{
perror("Error on select.\n");
exit(1);
}
else if (rv==0 && c!=1)
{
printf("timeout.\n");
rv=select(fd_stdin+1,&rd,NULL,NULL,&tv);
c=1;
}
else
{
c=0;
read(fd_stdin,command,10);
}
}
while(elapsed < seconds);
return 0;
}
函数,我这样编译:
fmod()
。我不认为这是问题,但我不确定。gcc client.c -lm -o client.exe
在退出时修改
select()
以反映已发出信号的描述符。每次超时后,您不会重置 fd_set
。此外,在某些平台上,
fd_set
会修改
select()
结构以反映剩余时间,因此每次在这些平台上调用 timeval
时,您都必须重置 timeval
。此外,您的
select()
变量是在循环内声明的并且未初始化。将其移到循环之外。
尝试更多类似这样的事情:
c