void epollEngine::MessageLoop() { const static int maxevents = 1024; struct epoll_event events[1024]; int nfds, i; BaseSocket * s; while(m_running) { nfds = epoll_wait(epoll_fd, events, maxevents, 1000); for(i = 0; i < nfds; ++i) { s = fds[events[i].data.fd]; if(s == 0) { printf("epoll returned invalid fd %u\n", events[i].data.fd); continue; } if(events[i].events & EPOLLHUP || events[i].events & EPOLLERR) { s->OnError(errno); } else if(events[i].events & EPOLLIN) { s->OnRead(0); if(s->Writable() && !s->m_writeLock) { ++s->m_writeLock; WantWrite(s); } } else if(events[i].events & EPOLLOUT) { s->OnWrite(0); if(!s->Writable()) { /* change back to read state */ struct epoll_event ev; memset(&ev, 0, sizeof(epoll_event)); ev.data.fd = s->GetFd(); ev.events = EPOLLIN | EPOLLET; epoll_ctl(epoll_fd, EPOLL_CTL_MOD, s->GetFd(), &ev); --s->m_writeLock; } } } } }
void kqueueEngine::MessageLoop() { const static int maxevents = MAX_DESCRIPTORS; timespec timeout; timeout.tv_sec = 1; timeout.tv_nsec = 0; struct kevent events[MAX_DESCRIPTORS]; struct kevent ev; int nfds, i; BaseSocket * s; while(m_running) { nfds = kevent(kq, 0, 0, events, maxevents, &timeout); for(i = 0; i < nfds; ++i) { s = fds[events[i].ident]; if(s == 0) { printf("kqueue returned invalid fd %u\n", events[i].ident); continue; } if(events[i].flags & EV_EOF || events[i].flags & EV_ERROR) { s->OnError(events[i].fflags); continue; } if(events[i].filter == EVFILT_READ) { s->OnRead(0); if(s->Writable() && !s->m_writeLock) { ++s->m_writeLock; WantWrite(s); } } else if(events[i].filter == EVFILT_WRITE) { s->OnWrite(0); if(!s->Writable()) { --s->m_writeLock; EV_SET(&ev, s->GetFd(), EVFILT_READ, EV_ADD, 0, 0, NULL); if(kevent(kq, &ev, 1, NULL, 0, NULL) < 0) printf("!! could not modify kevent (to read) for fd %u\n", s->GetFd()); } else { EV_SET(&ev, s->GetFd(), EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, NULL); if(kevent(kq, &ev, 1, NULL, 0, NULL) < 0) printf("!! could not modify kevent (to write) for fd %u\n", s->GetFd()); } } else { printf("Unknwon filter: %u Fflags: %u, fd: %u, flags: %u\n", events[i].filter, events[i].fflags, events[i].ident, events[i].flags); } } } }