当我用g++ -std=c++11 <filename>
编译并运行下面的代码,并运行./a.out
并input一些文本来查看select调用将返回的内容(它应该返回1,因为当我input文字,然后可以读入文字)。 不知何故,我input的文本作为bash命令本身。 有人能解释为什么发生这种情况
#include <errno.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/time.h> int input_timeout (int filedes, unsigned int seconds) { fd_set set; struct timeval timeout; // Initialize the file descriptor set. FD_ZERO (&set); FD_SET (filedes, &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. return select (FD_SETSIZE, &set, NULL, NULL, &timeout); } int main () { fprintf (stderr, "select returned %d.\n", input_timeout (STDIN_FILENO, 1)); return 0; }
所以上面我所说的一个例子就是在下面的输出中
bash-3.2 $ ./a.out what select returned 1. bash-3.2$ what
然后无限期地等待inputwhat
命令
您只检查是否有输入可用于从标准输入读取,但实际上没有读取它,因此它保留在终端缓冲区中。