<PAGE546>
#include <sys/select.h >
int select(int maxfdp1, fd_set *restrictreadfds,
fd_set *restrict writefds, fd_set *restrict exceptfds,
struct timeval *restrict tvptr)
select():
do I/O multiplexing (用于检测多个文件句柄的变化)
tvptr:
struct timeval {
long tv_sec;
longtv_usec;
}
tvptr==NULL
Wait forever. This infinite wait can be interruptedifwe catch a signal. Return is made when one of the specified descriptors isready or when a signal is caught. Ifa signal is caught, selectreturns –1 witherrnoset to EINTR. (永远等待,直到文件描述符就绪或信号被捕获,selcet处于堵塞状态)
tvptr->tv_sec==0 && typtr->tv_usec==0
Don't wait at all.All the specified descriptors are tested, and return is made immediately. Thisis away to poll the system to find out the status of multiple descriptors,without blocking in the select function. (用于测试文件描述符的状态,select并不堵塞)
tvptr->tv_sec!=0|| tv->tv_usec!=0
Wait the specified number of seconds andmicroseconds. Return is made when one of the specified descriptors is ready orwhen the timeout value expires. can also be interrupted by a caught signal(等待指定的时间,当文件描述符就绪或者时间超时,则返回)
readfdswritefds exceptfds:
These three sets specify which descriptors we're interested inand for which conditions.
can benull pointers if we're not interested in that condition (fd_set 的变量)
maxfdp1:
stands for "maximum file descriptor plus1.
calculate the highest descriptor that we're interested in,considering all three of the descriptor sets, add 1. (输入最大的文件描述符+1,内核会根据这个变量遍历查找fd_set的文件描述符,看是否有就绪状态的文件描述符,返回给user app层)
return:
count of ready descriptors, 0 on timeout, –1 on error
remarks:
A descriptor in the read set (readfds) is consideredready if a read from that descriptor won't block
Adescriptor in the write set (writefds) is considered ready if a writeto thatdescriptor won't block
Adescriptor in the exception set (exceptfds) is considered ready if an exceptioncondition is pendingon that descriptor.
本文详细解析了select()函数的用法,包括其核心功能、参数tvptr的作用及不同参数设置下函数的行为。重点阐述了如何利用select()进行多路复用I/O操作,以及在不同场景下选择合适的参数设置以实现高效的数据读写。
7569

被折叠的 条评论
为什么被折叠?



