Use poll Instead of select for Many Descriptors
Replace select with poll and struct pollfd to serve many clients in C without the FD_SETSIZE limit, and learn the POLLIN, POLLHUP and POLLNVAL revents.

select works until a descriptor number reaches 1024, and then it does not. A process that has opened a few hundred files and sockets can hit that wall with far fewer than 1024 clients, because the limit applies to the descriptor's number and not to how many you are watching. poll removes the ceiling by changing the data structure: instead of a fixed bitmap, you pass an array of struct pollfd, and the call sleeps until one of them is ready. This post converts the select-based echo server to poll and explains what the revents field reports, using Linux 6.12 and glibc 2.40.
The interface
poll is defined by POSIX and documented in poll(2):
#include <poll.h>
struct pollfd {
int fd; /* descriptor to watch */
short events; /* events you ask for */
short revents; /* events that happened, filled in by the kernel */
};
int poll(struct pollfd *fds, nfds_t nfds, int timeout);You pass the array, its length and a timeout in milliseconds (-1 waits forever, 0 returns immediately). The return value is the number of entries with a nonzero revents, 0 on timeout and -1 on error.
Two design choices already fix most of select's irritations. The request lives in events and the answer in revents, so the kernel never overwrites what you asked for, and there is no copy-the-master-set step. And nfds is the array length, so no descriptor number can fall outside the structure: a descriptor of 5000 is fine.
Events you ask for and events you get
You set events to a bitmask of what interests you. The common values are POLLIN (data to read, or a connection to accept) and POLLOUT (room to write). The kernel sets revents to what actually happened, and it can set three flags you never asked for:
| Flag | Meaning |
|---|---|
POLLERR | an error occurred on the descriptor |
POLLHUP | the peer hung up (for a stream socket, usually together with POLLIN if data remains) |
POLLNVAL | the descriptor is not open, which usually means a bug in your bookkeeping |
A negative fd in an entry makes poll skip it and report revents as 0. That is the supported way to remove a client from the array without compacting it, and the program below uses it.
An echo server using poll
The array holds the listener at index 0 and clients after it. Free slots have fd = -1.
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define MAX_FDS 4096
static struct pollfd fds[MAX_FDS];
int main(void)
{
int srv = socket(AF_INET, SOCK_STREAM, 0);
int one = 1;
setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
struct sockaddr_in a = {
.sin_family = AF_INET,
.sin_port = htons(7002),
.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
};
if (bind(srv, (struct sockaddr *)&a, sizeof a) < 0 || listen(srv, 128) < 0) {
perror("bind/listen");
return 1;
}
for (int i = 0; i < MAX_FDS; i++)
fds[i].fd = -1;
fds[0].fd = srv;
fds[0].events = POLLIN;
int used = 1; /* entries 0..used-1 are in play */
puts("listening on 127.0.0.1:7002");
for (;;) {
int ready = poll(fds, (nfds_t)used, -1);
if (ready < 0) {
if (errno == EINTR)
continue;
perror("poll");
return 1;
}
if (fds[0].revents & POLLIN) {
int c = accept(srv, NULL, NULL);
if (c >= 0) {
int slot = -1;
for (int i = 1; i < used; i++)
if (fds[i].fd < 0) { slot = i; break; }
if (slot < 0 && used < MAX_FDS)
slot = used++;
if (slot < 0) {
close(c);
} else {
fds[slot].fd = c;
fds[slot].events = POLLIN;
fds[slot].revents = 0;
printf("client connected (fd %d, slot %d)\n", c, slot);
}
}
}
for (int i = 1; i < used; i++) {
if (fds[i].fd < 0 || fds[i].revents == 0)
continue;
if (fds[i].revents & (POLLERR | POLLNVAL)) {
close(fds[i].fd);
fds[i].fd = -1;
continue;
}
if (fds[i].revents & (POLLIN | POLLHUP)) {
char buf[512];
ssize_t n = read(fds[i].fd, buf, sizeof buf);
if (n > 0) {
write(fds[i].fd, buf, (size_t)n);
} else {
printf("client closed (fd %d)\n", fds[i].fd);
close(fds[i].fd);
fds[i].fd = -1;
}
}
}
}
}Note what is absent compared with the select version: no per-iteration rebuild, no maxfd, no FD_SET. The array persists between calls and poll only writes revents. Closing a client is fd = -1, and the used high-water mark keeps poll from scanning the unused tail of the 4096-entry array.
A session with two nc 127.0.0.1 7002 clients, one of which disconnects, prints lines like these (descriptor numbers can differ on your machine):
listening on 127.0.0.1:7002
client connected (fd 4, slot 1)
client connected (fd 5, slot 2)
client closed (fd 5)
client closed (fd 4)Why test POLLHUP together with POLLIN
When a client closes its end, Linux typically reports POLLIN together with POLLHUP on a stream socket, because the socket is both readable (the read will return 0) and hung up. Treating POLLHUP as a reason to call read is what discovers the end of stream and any final bytes still buffered. Closing on POLLHUP alone can drop the last chunk of data the client sent before closing. The loop above reads on either flag and closes only when read returns 0 or fails.
For a half-closed connection where the peer shut down its write side, newer kernels also offer POLLRDHUP (Linux 2.6.17, requires _GNU_SOURCE), which reports that the peer closed its writing half. It lets you detect the shutdown without a read.
What poll does not fix
poll removes the descriptor-number ceiling, but not the cost model. Each call still passes the whole array into the kernel, and the kernel checks every entry. Your own loop then scans all entries for a nonzero revents. For 100 descriptors that is cheap. For 50,000 mostly idle descriptors, the work per wakeup grows with the total rather than with the number of ready ones, which is why Linux has epoll, covered in the epoll event loop post. poll and select are both O(n) in the number of watched descriptors per call.
There is also a small portability difference worth knowing. poll exists on all POSIX systems, but older macOS releases had a broken poll for devices and some other special files, and Windows only gained WSAPoll with its own historical quirks. If you target macOS and BSD for heavy use, kqueue is the better native choice.
Timeouts
The timeout is an integer number of milliseconds, which is coarser to write than select's timeval but easier to use:
int ready = poll(fds, (nfds_t)used, 5000); /* wait at most 5 seconds */
if (ready == 0) {
/* timeout: run idle-connection cleanup */
}Linux also has ppoll, which takes a struct timespec for nanosecond resolution and a signal mask to swap in atomically, solving the race between checking a "stop" flag set by a signal handler and going to sleep.
Choosing between select, poll and epoll
select | poll | epoll | |
|---|---|---|---|
| Descriptor limit | FD_SETSIZE (1024) on the number | none | none |
| Per-call work | O(n) scan | O(n) scan | O(ready) |
| Set kept by | you, rebuilt each call | you, array persists | the kernel |
| Portability | everywhere | POSIX systems | Linux only |
Pick poll for hundreds of descriptors or for portable POSIX code, and move to epoll or kqueue when the connection count is large and most of them are idle.
Handling writes with POLLOUT
An echo server can write straight after reading because small replies fit in the socket buffer. A server that sends large responses cannot assume that. When write accepts fewer bytes than offered, or fails with EAGAIN on a non-blocking socket, keep the remainder in a per-connection buffer and set POLLOUT in that entry's events. poll then reports the descriptor when the kernel has room again, you send more, and when the buffer is empty you clear POLLOUT. Leaving POLLOUT set on an idle socket makes poll return immediately every time, because a socket with buffer space is always writable, and the loop turns into a busy wait that uses a full core while doing nothing useful.
Converting an existing select loop
The mapping from select is mechanical, which is why poll is the usual first step for code that has outgrown the descriptor limit. The read set becomes entries with POLLIN, the write set becomes entries with POLLOUT, and the exception set, which select rarely uses in practice except for out-of-band TCP data, maps to POLLPRI. The copy of the master set disappears, the maxfd bookkeeping disappears, and the FD_ISSET tests become bit tests on revents. Keep a single array and a high-water mark, and compact it only when many entries are free, since scanning a few empty slots costs less than moving memory.
Growing the array
The program above uses a fixed array of 4096 entries, which is a deliberate simplification. A production server allocates the array with realloc and doubles it when full, which is safe because poll takes the pointer on each call and holds no state between calls. That is a real advantage over epoll, where the kernel keeps the interest list and you must tell it about every change. If your descriptor churn is high and the set is small, the stateless model of poll is simpler to reason about, with nothing to leak and nothing to forget to remove.

