开发者

How do I implement epoll timeout?

I am working on a network programming using epoll. It seems like working fine. I would like to add a timeout function so if a client doesn't sent开发者_如何转开发 anything for a long period time then it will just disconnect the client.

How do I do this? I know that I can set the timeout in epoll_wait but this is not for the individual socket...

Thanks in advance...


Keep a list of the sockets sorted by the time remaining until they time out (if the timeout period is the same for all sockets, then this is equivalent to sorting them by the time of the last recieved message). Each time you call epoll_wait(), select the socket with the shortest remaining time until it times out (which will be at the front of your list). Use that time as the timeout in epoll_wait().

When epoll_wait() returns, after processing any active sockets, go through the sorted list of sockets pruning all the expired ones (which will be at the start of the sorted list).


At epoll_wait() time:

timeout = expirylist->expire_time - current_time();
n_events = epoll_wait(epfd, events, maxevents, timeout);

handle_events(events, n_events);

for (client = expirylist; client != NULL && client->expire_time < current_time(); client = client->expire_next)
{
    do_timeout(client);
}


You can create a recurring timerfd and add it to your epoll set. It will wake you up however often you like, at which point you can check all your client connections and drop the ones you think are stale.

If your Linux is too old to support timerfd, you could try the older timer_create.


Just use libevent* or similar; this will save the effort of implementing your own queues and checking timeouts. It may also make your use of epoll easier, and as an added benefit be somewhat more portable (say you want to run your app on FreeBSD, which has no epoll but has something conceptually similar called kqueue)

* other similar libraries are available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜