这是把fd_set相关的源代码汇总在一起。这样应该知道fd_set的实现详细原理
define FD_SETSIZE 1024
typedef unsigned long fd_mask;
#define NBBY 8 /* number of bits in a byte */
#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */
#define howmany(x, y) (((x) + ((y) - 1)) / (y))
typedef struct fd_set {
fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)];
} fd_set;
#define _fdset_mask(n) ((fd_mask)1 << ((n) % NFDBITS))
#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= _fdset_mask(n))
#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~_fdset_mask(n))
#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & _fdset_mask(n))
#define FD_COPY(f, t) bcopy(f, t, sizeof(*(f)))
#define FD_ZERO(p) bzero(p, sizeof(*(p)))
fd_set master_set_read;
FD_SET(600,master_set_read);
=> master_set_read->fds_bits[(600)/32] |= (1<<(600%32));
定义如下:
#ifndef FD_SETSIZE
#define FD_SETSIZE 64
#endif /* FD_SETSIZE */
typedef struct fd_set {
u_int fd_count; /* how many are SET? */
SOCKET fd_array[FD_SETSIZE]; /* an array of SOCKETs */
} fd_set;
下面在看看几个宏的定义:
FD_SET 打开类型fd_set的某一位
FD_ZERO初始化fd_set
FD_ISSET测试结构fd_set中的描述字
#define FD_CLR(fd, set) do { /
u_int __i; /
for (__i = 0; __i < ((fd_set FAR *)(set))->;fd_count ; __i++) { /
if (((fd_set FAR *)(set))->;fd_array[__i] == fd) { /
while (__i < ((fd_set FAR *)(set))->;fd_count-1) { /
((fd_set FAR *)(set))->;fd_array[__i] = /
((fd_set FAR *)(set))->;fd_array[__i+1]; /
__i++; /
} /
((fd_set FAR *)(set))->;fd_count--; /
break; /
} /
} /
} while(0)
#define FD_SET(fd, set) do { /
u_int __i; /
for (__i = 0; __i < ((fd_set FAR *)(set))->;fd_count; __i++) { /
if (((fd_set FAR *)(set))->;fd_array[__i] == (fd)) { /
break; /
} /
} /
if (__i == ((fd_set FAR *)(set))->;fd_count) { /
if (((fd_set FAR *)(set))->;fd_count < FD_SETSIZE) { /
((fd_set FAR *)(set))->;fd_array[__i] = (fd); /
((fd_set FAR *)(set))->;fd_count++; /
} /
} /
} while(0)
#define FD_ZERO(set) (((fd_set FAR *)(set))->;fd_count=0)
#define FD_ISSET(fd, set) __WSAFDIsSet((SOCKET)(fd), (fd_set FAR *)(set))