/*
函数说明:正常每隔一秒打印一个数字,当有fd被设置时,就马上执行操作。而不是被阻塞住
*/
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <error.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PATH "test.txt"
int T_select(void);
int main(void)
{
int i=0;
for(;i<100;i++)
{
printf("i=%d\n",i);
sleep(1);
T_select();
}
//异步复用IO处理
return 0;
}
int T_select(void)
{
int n =-1,fd = -1;
char buf[100];
fd_set MY_FD_SET;
struct timeval timeout;
//fd = open(PATH,O_RDONLY);
FD_ZERO(&MY_FD_SET);
//FD_SET(fd,&MY_FD_SET);
FD_SET(0,&MY_FD_SET); //换为键盘标准IO输入更形象
timeout.tv_sec = 10; //10S定时
timeout.tv_usec=0;
n = select(0+1, &MY_FD_SET, NULL, NULL, &timeout);
if (n < 0)
{
perror("select");
}
else if(n==0) //10S没有fd设置
{
printf("timeout\n");
}
else //有fd被设置,变为非阻塞式
{
if(FD_ISSET(0,&MY_FD_SET))
{
memset(buf,0,sizeof(buf));
read(0,buf,10);
printf("read files:%s\n",buf);
}
}
return 0;
}
/*
函数原型:
int select(int nfds,fd_set *readfds,fd_set *writefds,fd_set *exceptfds,struct timeval *timeout);
功能:select可以根据内部设置的多个fd,那个fd被设置就会去执行相关操作。可以起到异步多路复用IO的功能,提供函数执行效率。select本身是阻塞式的,直到收到有fd被设置才变为非阻塞式。
异常:如果在设定时间内,select没有收到fd的返回值,则返回0,表示超时。正常返回最大fd+1的值,出错则返回小于零的负数。
使用:结合这四个个宏:FD_CLR、FD_ISSET、FD_ZERO、FD_SET。其中FD_ISSET是判断那个fd被设置了。
注意:struct timeval timeout;超时时间设置必须在FD_CLR、FD_SET之后,不然会报错,一开始没有注意这个问题,发生离奇的错误,先把struct timeval timeout的值放在FD_CLR、FD_SET之前,报一个select参数不合法,所以写程序的思路还是要很清晰的。
*/