Handle Multiple Clients with select
Build a single-threaded C echo server that serves many clients with select, fd_set, FD_SET and FD_ISSET, and learn why you rebuild the set on every loop.

A blocking read can only wait on one client, so a server that wants to serve ten of them needs ten threads or a way to ask the kernel which of the ten has something to say. select is that way. It is the oldest of the readiness APIs, it exists on every POSIX system and on Windows, and it is the right first one to learn because the later APIs (poll, epoll, kqueue) keep the same idea with better ergonomics. In this post you build a single-threaded echo server that handles many clients with select, on Linux 6.12 and glibc 2.40. Where fork per connection gives each client a process, this version serves them all from one loop.
What select does
select takes up to three sets of descriptors, one to watch for readability, one for writability and one for exceptional conditions, plus an optional timeout. It sleeps until at least one descriptor in a set is ready or the timeout expires, then returns the number of ready descriptors and rewrites each set so it contains only the ready ones. The select(2) and POSIX pages define it:
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);nfds is the highest descriptor number in any set plus one, not the count of descriptors. Forgetting the plus one makes the highest descriptor silently ignored. The sets are manipulated with four macros: FD_ZERO(&set) empties it, FD_SET(fd, &set) adds a descriptor, FD_CLR(fd, &set) removes one and FD_ISSET(fd, &set) tests whether it is in the set after the call.
The one trap everyone hits
select modifies the sets you pass in. After it returns, a set holds only the ready descriptors, and the rest are gone. So the sets cannot be reused as they are. The usual pattern keeps a master set that records everything you are watching, and copies it into a scratch set before each call:
fd_set master, ready;
FD_ZERO(&master);
...
ready = master; /* fd_set is a plain struct: copy it */
select(maxfd + 1, &ready, NULL, NULL, NULL);Skip the copy and the second iteration watches nothing, which looks like a server that serves one event and then stops responding.
An echo server for many clients
The server below keeps one listening socket and an array of client sockets. A readable listener means a new connection is waiting; a readable client means data, or an end of file, is waiting.
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#define MAX_CLIENTS 64
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(7001),
.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
};
if (bind(srv, (struct sockaddr *)&a, sizeof a) < 0 || listen(srv, 16) < 0) {
perror("bind/listen");
return 1;
}
int clients[MAX_CLIENTS];
for (int i = 0; i < MAX_CLIENTS; i++)
clients[i] = -1;
puts("listening on 127.0.0.1:7001");
for (;;) {
fd_set ready;
FD_ZERO(&ready);
FD_SET(srv, &ready);
int maxfd = srv;
for (int i = 0; i < MAX_CLIENTS; i++) {
if (clients[i] >= 0) {
FD_SET(clients[i], &ready);
if (clients[i] > maxfd)
maxfd = clients[i];
}
}
if (select(maxfd + 1, &ready, NULL, NULL, NULL) < 0) {
if (errno == EINTR)
continue;
perror("select");
return 1;
}
if (FD_ISSET(srv, &ready)) {
int c = accept(srv, NULL, NULL);
if (c >= 0) {
int slot = -1;
for (int i = 0; i < MAX_CLIENTS; i++)
if (clients[i] < 0) { slot = i; break; }
if (slot < 0) {
close(c); /* table full: refuse politely */
} else {
clients[slot] = c;
printf("client %d connected (fd %d)\n", slot, c);
}
}
}
for (int i = 0; i < MAX_CLIENTS; i++) {
int c = clients[i];
if (c < 0 || !FD_ISSET(c, &ready))
continue;
char buf[512];
ssize_t n = read(c, buf, sizeof buf);
if (n > 0) {
write(c, buf, (size_t)n);
} else {
printf("client %d closed (fd %d)\n", i, c);
close(c);
clients[i] = -1;
}
}
}
}This version rebuilds the set from the client table on every pass, which has the same effect as a master set and is simple to read. Compile with gcc -O2 -Wall select_echo.c -o select_echo.
If two terminals each run nc 127.0.0.1 7001, connect, type a line and then quit, the server prints something like this. The descriptor numbers can differ on your system, because they depend on what else the process has open.
listening on 127.0.0.1:7001
client 0 connected (fd 4)
client 1 connected (fd 5)
client 1 closed (fd 5)
client 0 closed (fd 4)While client 0 is idle, client 1 is served immediately, because the server never sleeps inside a read. It sleeps in select, and select wakes for whichever descriptor speaks first. A read that returns 0 is the peer closing; a negative return (other than EAGAIN, which cannot happen here after readiness) is an error. Both lead to closing the descriptor and freeing the slot.
Why read will not block here
The descriptor was reported readable, so a single read returns immediately with whatever is buffered, up to the buffer size. That is why this loop works with plain blocking sockets. It is also a place where select can mislead: Linux's select(2) page warns that a descriptor reported readable may still block on a later call in rare cases, for example when a received packet fails a checksum and is discarded after the wakeup. For descriptors that must never block, combine select with O_NONBLOCK, as covered in making a socket non-blocking.
Limits and costs
Two limits come with select, and both are reasons to move on later.
A fixed ceiling. fd_set is a bitmap with room for FD_SETSIZE descriptors, which is 1024 on Linux with glibc. A descriptor number of 1024 or more cannot go in a set, and writing it with FD_SET is undefined behavior, so a server whose process has opened many files may hit this long before it has 1024 clients. The origin of that number is its own story, told in how fd_set bitmaps work.
Linear cost. Each call copies the sets into the kernel and scans them, and your own loop then scans them again. The cost per call grows with the number of descriptors watched, not the number ready. With 50 clients that is nothing; with 10,000, mostly idle, it is the reason epoll was written.
Timeouts and housekeeping
The last argument limits the wait. Pass a struct timeval for a bounded sleep, or NULL to wait forever. A common use is a periodic tick for idle-connection cleanup:
struct timeval tv = { .tv_sec = 5, .tv_usec = 0 };
int n = select(maxfd + 1, &ready, NULL, NULL, &tv);
if (n == 0) {
/* five seconds with no activity: sweep idle clients */
}On Linux select modifies tv to show the time left, so rebuild it before every call. POSIX does not promise that behavior, and portable code never relies on it either way.
When select is still the right choice
Use select for a small tool with a handful of descriptors, for code that must run on both POSIX and Windows with minimal changes, or for the teaching loop in this post. Use poll when you want to drop the 1024 ceiling without changing architecture, and epoll or kqueue when the client count is large and mostly idle.
Reading the loop one step at a time
It helps to trace one pass of the server with two clients attached, client A idle and client B sending a line. At the top of the loop the program builds a set containing the listener, A and B, and calls select. A has sent nothing and the listener has no pending connection, so neither is ready. B has data, so select returns 1 and leaves only B in the set. The accept test fails, the loop over clients skips A because FD_ISSET is false, and for B it reads the line and writes it back. The next iteration starts from scratch with all three descriptors again. A's silence cost nothing, because the thread was asleep inside select rather than inside a read on A, and that is the single idea this whole post is about.
Handling many descriptors becoming ready at once
If clients A and B both send data before the server wakes, select returns 2 and both are marked, and the loop serves them in table order within the same pass. Nothing is lost, and the order is fair enough for an echo server. A heavier server needs to guard against one client monopolizing a pass, usually by capping the bytes handled per descriptor per iteration and leaving the remainder for the next wake. Because select is level-triggered, unread data is simply reported again.
Common mistakes with select
**Passing the descriptor count as
nfds.** The parameter is the highest number plus one. Using the count of clients works by accident on a quiet process and fails when the descriptors are not contiguous.**Forgetting
EINTR.** A signal can interruptselect, which then returns-1witherrnoset toEINTRand leaves the sets undefined, so retry after rebuilding them.Closing a descriptor but leaving it in the table. The next pass passes a closed descriptor to
select, which fails withEBADF. Set the slot to-1immediately, as the program does.**Calling
FD_SETwith a descriptor of 1024 or more.** The macro writes outside the bitmap, corrupting memory without any error.

