以下代码是添加和删除fd的代码,实现的很巧妙。
static void
select_add_fd( int fd, int rw ){
if ( nselect_fds >= nfiles )
{
syslog( LOG_ERR, "too many fds in select_add_fd!" );
return;
}
select_fds[nselect_fds] = fd; // 队列存放的是连接的fd
switch ( rw )
{
case FDW_READ: FD_SET( fd, &master_rfdset ); break;
case FDW_WRITE: FD_SET( fd, &master_wfdset ); break;
default: break;
}
if ( fd > maxfd )
maxfd = fd;
select_fdidx[fd] = nselect_fds;// 存放的是在fd对应在队列里面的值
++nselect_fds;
}
static void
select_del_fd( int fd )
{
int idx = select_fdidx[fd];
if ( idx < 0 || idx >= nfiles )
{
syslog( LOG_ERR, "bad idx (%d) in select_del_fd!", idx );
return;
}
--nselect_fds;
select_fds[idx] = select_fds[nselect_fds];
select_fdidx[select_fds[idx]] = idx;
select_fds[nselect_fds] = -1;
select_fdidx[fd] = -1;
FD_CLR( fd, &master_rfdset );
FD_CLR( fd, &master_wfdset );
if ( fd >= maxfd )
maxfd_changed = 1;
}
两个数组实现了一个快速队列的问题。