简体   繁体   English

如何停止epoll_wait?

[英]How to stop epoll_wait?

I just started coding in Linux and need to port my Win server code here using epoll .我刚开始在 Linux 编码,需要使用epoll在此处移植我的 Win 服务器代码。 I can't figure out how to stop epoll_wait .我不知道如何停止epoll_wait

The epoll loop runs in separate thread(s) and the main function handles console commands. epoll 循环在单独的线程中运行,主要的 function 处理控制台命令。 I need to stop the server after "quit" command is entered.输入“退出”命令后,我需要停止服务器。 Simply closing the master socket has no effect.简单地关闭主套接字没有任何效果。 So how to stop epoll correctly in this case (maybe cause somehow epoll_wait to return error in all threads)?那么在这种情况下如何正确停止 epoll(可能导致epoll_wait在所有线程中以某种方式返回错误)?

Usually, you put a special file descriptor in the epoll list of file descriptors.通常,你会在文件描述符的epoll列表中放置一个特殊的文件描述符。 An eventfd or a pipe are good candidates. eventfd管道是不错的选择。 Whenever you need to interrupt epoll_wait , you signal that file descriptor and in the event handling loop you check that file descriptor as the loop exit criteria.每当您需要中断epoll_wait ,您都会向该文件描述符发出信号,并在事件处理循环中检查该文件描述符作为循环退出标准。

Alternatively you could close epoll fd from another thread and fire a SIGINT which you can just ignore and then when epoll_wait restart, since efd is no longer valid, it will return -1 and set errno to EINVAL so you can exit epoll thread.或者你可以从另一个线程关闭 epoll fd 并触发一个你可以忽略的 SIGINT 然后当 epoll_wait 重新启动时,因为 efd 不再有效,它将返回 -1 并将 errno 设置为 EINVAL 这样你就可以退出 epoll 线程。

int efd;
pthread_t ethread;
        
void terminate_epoll( void )
{
    close( efd );
    pthread_kill( ethread, SIGINT );
    pthread_join( ethread, NULL );
}
      
void* epoll_thread( void* data )
{
    for(;;)
    {
        n = epoll_wait( efd, events, EPOLL_EVENT_COUNT, -1 );
        if( n == -1 )
        {
        if( errno == EINTR )
            continue;
        if( errno == EINVAL )
            goto end;
        ...
            
        }
    }
end:
    return NULL;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM