select() - Unix Linux System Call
select() 是用来测试文件是否已经准备好读或写, 当一个或多个文件准备好了时返回,可以设置等待时间,返回值是准备好的文件个数,或0(超过等待时间),或-1(出错)。
这是一个系统调用。 Want to know more
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
fd_set rfds;
struct timeval tv;
int retval;
char str[1024];
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don’t rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
{
printf("Data is available now.\n");
scanf("%s",str);
printf("%s\n",str);
/* FD_ISSET(0, &rfds) will be true. */
}
else
printf("No data within five seconds.\n");
return 0;
}