根据系统及其工作方式,您可以尝试将 select 函数与 STDIN 一起用作文件句柄。您可以将 select 语句上的时间设置为零以轮询以查看是否有数据或将其设置为等待时间。
你可以看看链接http://www.gnu.org/s/libc/manual/html_node/Waiting-for-I_002fO.html使用带有套接字的 select 语句的示例。
我已修改该示例以使用 STDIN 作为文件描述符。如果没有挂起的输入,该函数将返回 0,如果有挂起的输入(即有人按下输入键盘上的键),则返回 1,如果出现某种性质的错误,则返回 -1
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
int waitForKBInput(unsigned int seconds)
{
/* File descriptor set on which to wait */
fd_set set;
/* time structure which indicate the amount of time to
wait. 0 will perform a poll */
struct timeval timeout;
/* Initialize the file descriptor set. */
FD_ZERO (&set);
/* Use the Standard Input as the descriptor on which
to wait */
FD_SET (STDIN, &set);
/* Initialize the timeout data structure. */
timeout.tv_sec = seconds;
timeout.tv_usec = 0;
/* select returns 0 if timeout, 1 if input available, -1 if error. */
/* and is only waiting on the input selection */
return select (FD_SETSIZE,
&set, NULL, NULL,
&timeout));
}
我知道这在 VMS 系统上不起作用,因为我尝试了这个并且他们以不同的方式实现了 Select 和 STDIN,因此它不起作用(必须使用其他方法来检测键盘输入)。
对于 Visual C/C++ 可以使用函数 kbhit 来指示是否有要读取的键盘输入。