五,主IO复用
这是一个很主要的,就是IO复用机制。下面分析一下这个,这个是通过在模块上层应用,通过指定mio_st结构和一个超时时间。
- static void _mio_run(mio_t m, int timeout)
- {
- int retval;
- int iter;
- mio_debug(ZONE, "mio running for %d", timeout);
- /* wait for a socket event */
- retval = MIO_CHECK(m, timeout); // 这个宏是IO策略相关的,在IO策略是epoll时,这个宏最后展开是:epoll_wait(MIO(m)->epoll_fd,MIO(m)->res_event, 32, t*1000);看到这个,大家就明白了是怎么回事了。
- /* nothing to do */
- if(retval == 0) return;
- /* an error */
- if(retval < 0)
- {
- return;
- }
- /* loop through the sockets, check for stuff to do */
- MIO_ITERATE_RESULTS(m, retval, iter)
- {
- mio_fd_t fd = MIO_ITERATOR_FD(m,iter);
- if (fd == NULL) continue;
- /* skip already dead slots */
- if(FD(m,fd)->type == type_CLOSED) continue;
- /* new conns on a listen socket */
- if(FD(m,fd)->type == type_LISTEN && MIO_CAN_READ(m,iter))
- {
- _mio_accept(m, fd);
- continue;
- }
- /* check for connecting sockets */
- if(FD(m,fd)->type & type_CONNECT &&
- (MIO_CAN_READ(m,iter) || MIO_CAN_WRITE(m,iter)))
- {
- _mio__connect(m, fd);
- continue;
- }
- /* read from ready sockets */
- if(FD(m,fd)->type == type_NORMAL && MIO_CAN_READ(m,iter))
- {
- /* if they don't want to read any more right now */
- if(ACT(m, fd, action_READ, NULL) == 0)
- MIO_UNSET_READ(m, FD(m,fd));
- }
- /* write to ready sockets */
- if(FD(m,fd)->type == type_NORMAL && MIO_CAN_WRITE(m,iter))
- {
- /* don't wait for writeability if nothing to write anymore */
- if(ACT(m, fd, action_WRITE, NULL) == 0)
- MIO_UNSET_WRITE(m, FD(m,fd));
- }
- /* deferred closing fd
- * one of previous actions might change the state of fd */
- if(FD(m,fd)->type == type_CLOSED)
- {
- MIO_FREE_FD(m, fd);
- }
- }
- }
ACT宏展开后会调用mio_priv_fd_t 结构的app回调,这个是在模块的应用层上定义的。
FD宏用于将fd,转换成mio_priv_fd_t 结构,几个主要是的宏都是IO策略相关的,定义如下:
- #define MIO_ITERATE_RESULTS(m, retval, iter) \
- for(MIO(m)->defer_free = 1, iter = 0; (iter < retval) || ((MIO(m)->defer_free = 0)); iter++)
- #define MIO_ITERATOR_FD(m, iter) \
- (MIO(m)->res_event[iter].data.ptr)
- #define MIO_CAN_READ(m,iter) \
- (MIO(m)->res_event[iter].events & (EPOLLIN|EPOLLERR|EPOLLHUP))
- #define MIO_CAN_WRITE(m,iter) \
- (MIO(m)->res_event[iter].events & EPOLLOUT)
- #define MIO_CAN_FREE(m) (!MIO(m)->defer_free)
