该虚拟程序可能会帮助您:
#include <stdio.h>#include <unistd.h>#include <sys/time.h>#include <sys/types.h>#define WAIT 3int main (){ char name[20] = {0}; // in case of single character input fd_set input_set; struct timeval timeout; int ready_for_reading = 0; int read_bytes = 0; FD_ZERO(&input_set ); FD_SET(0, &input_set); timeout.tv_sec = WAIT; // WAIT seconds timeout.tv_usec = 0; // 0 milliseconds printf("Enter Username: (in %d seconds)n", WAIT); printf("Time start now!!!n"); ready_for_reading = select(1, &input_set, NULL, NULL, &timeout); if (ready_for_reading == -1) { printf("Unable to read your inputn"); return -1; } if (ready_for_reading) { read_bytes = read(0, name, 19); if(name[read_bytes-1]=='n'){ --read_bytes; name[read_bytes]=' '; } if(read_bytes==0){ printf("You just hit entern"); } else { printf("Read, %d bytes from input : %s n", read_bytes, name); } } else { printf(" %d Seconds are over - no data input n", WAIT); } return 0;}更新:
这是经过测试的代码。
另外,我从man那里得到了一些提示
select。本手册已包含一个代码段,该代码段可用于从终端读取内容,并且在无活动的情况下会在5秒内超时。
如果代码编写得不够好,请做一个简短的解释:
- 我们将输入流(
fd = 1
)添加到FD集。 - 我们发起
select
呼叫以侦听为任何活动创建的此FD集。 - 如果在此
timeout
期间内发生任何活动,则通过read
调用读取该活动。 - 如果没有活动,则会发生超时。
希望这可以帮助。



