/* epoll,主要为了同时使用多个epoll及其线程处理不同的socket集 by dzj, 09.06.04 */ #ifndef WIN32 #include "dsepoll.h" #include "lsocket.h" #include "sigexception/sigexception.h" void* DsEPollWaitThread( void* pInDsEPoll ) { ThreadInitTls(); if ( NULL == pInDsEPoll ) { return NULL; } sleep( 2 );//等待pInDsEPoll构造完成; CDsEPoll* pDsEPoll = (CDsEPoll*) pInDsEPoll; pDsEPoll->WaitTrdProc(); ThreadEndTls(); return NULL; }; CDsEPoll::CDsEPoll() { m_bIsStopWaitTrd = false; m_maxfd = 2048; m_arrPollEvents = NEW epoll_event[m_maxfd]; //建epoll句柄; m_epfd = epoll_create( m_maxfd ); if ( -1 == m_epfd ) { NewLog( LOG_LEV_ERROR, "CDsEPoll, epoll句柄创建失败\n" ); return; } m_polltrd = 0; int polltrderr = pthread_create( &m_polltrd, NULL, DsEPollWaitThread, (void*)this ); if ( 0 != polltrderr ) { NewLog( LOG_LEV_ERROR, "CDsEPoll(%x),创建epoll wait线程失败\n", (unsigned long)this ); return; } NewLog( LOG_LEV_INFO, "CDsEPoll(%x),创建epoll wait线程成功\n", (unsigned long)this ); }; CDsEPoll::~CDsEPoll() { NewLog( LOG_LEV_INFO, "CDsEPoll(%x),析构销毁epoll wait线程...\n", (unsigned long)this ); m_bIsStopWaitTrd = true;//由于只在此处写,因此不必考虑冲突; pthread_join( m_polltrd, NULL );//停对应线程; NewLog( LOG_LEV_INFO, "CDsEPoll(%x),析构销毁epoll wait线程,成功\n", (unsigned long)this ); close( m_epfd );//关epoll句柄; if ( NULL != m_arrPollEvents ) { delete [] m_arrPollEvents; m_arrPollEvents = NULL; } }; ///等待线程执行函数,返回false表示无需再循环; void CDsEPoll::WaitTrdProc() { while ( !m_bIsStopWaitTrd ) { CLSocket* pLSocket = NULL; int waitrst = -1; NewLog( LOG_LEV_INFO, "epoll wait start" ); waitrst = epoll_wait( m_epfd, m_arrPollEvents, m_maxfd, 5000/*to exit thread, -1,wait infinite*/ ); int tmperr = errno;//即刻取错误号; NewLog( LOG_LEV_INFO, "epoll wait end, waitrst:%d", waitrst ); if ( -1 == waitrst ) { NewLog( LOG_LEV_INFO, "epoll wait err : %d\n", tmperr ); if ( EBADF == tmperr ) { NewLog( LOG_LEV_WARNING, "EBADF\n" ); } else if ( EFAULT == tmperr ) { NewLog( LOG_LEV_WARNING, "EFAULT\n" ); } else if ( EINTR == tmperr ) { NewLog( LOG_LEV_WARNING, "EINTR\n" ); } else if ( EINVAL == tmperr ) { NewLog( LOG_LEV_WARNING, "EINVAL\n" ); } else { NewLog( LOG_LEV_WARNING, "unknown err:%d\n", tmperr ); } continue; } // -1 != waitrst ; ST_SIG_CATCH { for ( int i=0; iOnEPollEvent( m_arrPollEvents[i].events ); } }//遍历处理各epoll事件; } END_SIG_CATCH; } //while not stop; return; } #endif //#ifndef WIN32