Iceman
Iceman

Reputation: 397

How to stop epoll_wait?

I just started coding in Linux and need to port my Win server code here using epoll. I can't figure out how to stop epoll_wait.

The epoll loop runs in separate thread(s) and the main function handles console commands. 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)?

Upvotes: 1

Views: 2576

Answers (2)

mystackoverflowpseudo
mystackoverflowpseudo

Reputation: 75

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.

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;
}

Upvotes: 0

Andrey Semashev
Andrey Semashev

Reputation: 10614

Usually, you put a special file descriptor in the epoll list of file descriptors. An eventfd or a pipe are good candidates. 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.

Upvotes: 5

Related Questions