Day48 - Epoll + Timerfd + Idle Timeout¶
Overview¶
In this lab, we extend the epoll-based TCP server by integrating timerfd
to implement idle timeout handling for multiple clients.
The server now supports:
- Multi-client connection (epoll)
- Non-blocking sockets
- TX queue with partial send handling
- Periodic timer event using
timerfd - Idle timeout detection and automatic client cleanup
timerfd Basics¶
Key APIs¶
timerfd_create()timerfd_settime()read()
Important Concept¶
read(timerfd) does NOT return time.
It returns:
Example¶
timer interval = 1 sec
If read every second:
expirations = 1
If read after 5 seconds:
expirations = 5
Why timerfd with epoll?¶
Compared to other approaches:
| Method | Problem |
|---|---|
| sleep() | blocks thread |
| signal | complex, race conditions |
| thread timer | synchronization overhead |
timerfd advantages:
- file descriptor based
- works naturally with epoll
- no signal handling
- no extra thread
Idle Timeout Design¶
Architecture¶
timerfd (1 sec tick)
↓
epoll event loop
↓
scan all clients
↓
check idle time
↓
destroy timed-out clients
Key Design Choice¶
We use:
Instead of:
Trade-offs¶
| Approach | Pros | Cons |
|---|---|---|
| Global timer + scan | simple, scalable | O(N) scan |
| Per-client timerfd | precise timeout | complex, many fd |
Client Data Structure¶
struct client_ctx {
int fd;
uint64_t last_active_ms;
struct tx_queue txq;
struct client_ctx *next;
};
Server Data Structure¶
struct server_ctx {
int listen_fd;
int epoll_fd;
int timer_fd;
uint64_t timer_ms;
struct client_ctx *client_list;
};
Lifecycle Management¶
Accept¶
Activity Update¶
Timeout Detection¶
Destroy Client¶
epoll vs Client List¶
Important concept:
epoll only tells:
It does NOT track all active clients.
Time Source¶
We use:
Reasons:
- not affected by system time changes
- safe for timeout calculation
Timeout Precision¶
Timeout is not exact.
Example:
Summary¶
This lab introduces:
- fd-based timer (timerfd)
- integrating timer into epoll loop
- scalable idle timeout design
- clean client lifecycle management
This is a fundamental building block for real-world servers.