What you will learn
- The
select()API and its fourFD_*macros. - Why you must copy the descriptor set before every call.
- How to watch sockets and standard input together.
- The limits of
select()(FD_SETSIZE, signals, timeout updates) and when to preferpoll().
The API
select() predates poll() and is found everywhere, including Windows. Instead of an array of structs it uses bit sets of descriptors:
#include <sys/select.h>
int select(int nfds, /* highest fd in any set, plus 1 */
fd_set *readfds, /* watch for readability (or NULL) */
fd_set *writefds, /* watch for writability (or NULL) */
fd_set *exceptfds, /* exceptional conditions, rarely used */
struct timeval *timeout);/* NULL = wait forever */
FD_ZERO(&set); /* clear all bits */
FD_SET(fd, &set); /* add fd */
FD_CLR(fd, &set); /* remove fd */
FD_ISSET(fd, &set); /* is fd in the set? */
On return, select() has overwritten each set so it contains only the ready descriptors. It returns how many are ready, 0 on timeout, -1 on error.
That overwrite is the classic bug: if you pass your master set directly, you lose track of everybody who wasn’t ready. Always keep a master set and copy it:
fd_set ready = everyone; /* struct copy */
select(max_fd + 1, &ready, NULL, NULL, NULL);
Example: server with an operator console
This server prints whatever clients send, and anything the operator types into the server’s terminal is announced to every client. One select() watches the keyboard (STDIN_FILENO), the listener and all clients.
/* select_console.c - TCP server watched with select(), plus an operator console.
* Lines from clients are printed on the server; lines typed on the server's
* keyboard are sent to every client as announcements. Usage: ./select_console 7171 */
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
static int open_listener(const char *port)
{
struct addrinfo hints, *res, *ai;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(NULL, port, &hints, &res) != 0)
return -1;
int fd = -1;
for (ai = res; ai != NULL; ai = ai->ai_next) {
fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (fd == -1)
continue;
int on = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);
if (bind(fd, ai->ai_addr, ai->ai_addrlen) == 0 && listen(fd, 16) == 0)
break;
close(fd);
fd = -1;
}
freeaddrinfo(res);
return fd;
}
int main(int argc, char *argv[])
{
const char *port = argc > 1 ? argv[1] : "7171";
int listener = open_listener(port);
if (listener == -1) {
fprintf(stderr, "cannot listen on port %s\n", port);
return 1;
}
fd_set everyone; /* the master set we maintain */
FD_ZERO(&everyone);
FD_SET(STDIN_FILENO, &everyone);
FD_SET(listener, &everyone);
int max_fd = listener;
printf("listening on %s; type a line to announce it\n", port);
for (;;) {
fd_set ready = everyone; /* select() overwrites its argument */
struct timeval tick = { .tv_sec = 30, .tv_usec = 0 };
int n = select(max_fd + 1, &ready, NULL, NULL, &tick);
if (n == -1) {
if (errno == EINTR)
continue; /* a signal interrupted us: just retry */
perror("select");
return 1;
}
if (n == 0) {
printf("(30 s with no activity)\n");
continue;
}
for (int fd = 0; fd <= max_fd; fd++) {
if (!FD_ISSET(fd, &ready))
continue;
if (fd == listener) {
int client = accept(listener, NULL, NULL);
if (client == -1) {
perror("accept");
} else if (client >= FD_SETSIZE) {
close(client); /* select() cannot watch it */
} else {
FD_SET(client, &everyone);
if (client > max_fd)
max_fd = client;
printf("client on fd %d\n", client);
}
} else if (fd == STDIN_FILENO) {
char line[256];
if (fgets(line, sizeof line, stdin) == NULL)
return 0; /* operator pressed Ctrl-D */
for (int c = 0; c <= max_fd; c++)
if (c != listener && c != STDIN_FILENO && FD_ISSET(c, &everyone))
send(c, line, strlen(line), MSG_NOSIGNAL);
} else {
char buf[512];
ssize_t got = recv(fd, buf, sizeof buf, 0);
if (got <= 0) {
printf("fd %d disconnected\n", fd);
close(fd);
FD_CLR(fd, &everyone);
} else {
printf("fd %d: %.*s", fd, (int)got, buf);
fflush(stdout);
}
}
}
}
}
Highlights:
max_fd + 1.select()checks descriptors0tonfds - 1, so track the highest one you’ve added.- A 30-second timeout shows the idle path. On Linux,
select()modifies thetimevalto show the time left, so we re-create it each loop. Don’t rely on either behaviour; always reset it. FD_SETSIZEguard. Anfd_setholds descriptors belowFD_SETSIZE(usually 1024). CallingFD_SETwith a larger fd corrupts memory, so we refuse such clients.- EINTR. A signal (resizing the terminal can send one) makes
select()fail withEINTR; just loop again.
gcc -Wall -o select_console select_console.c
./select_console 7171
# another terminal:
nc localhost 7171
Type in nc and the server prints it; type in the server’s terminal and every nc sees the announcement.
”Readable” can mean end-of-stream
When a client disconnects, its socket becomes readable and recv() returns 0. That’s why the “readable” branch always checks for 0 and cleans up. The same holds for poll().
A subtle trap: select() and buffered stdin
We read stdin with fgets(). If the user pastes several lines at once, fgets() pulls them all into stdio’s buffer but returns only one; select() then sees an empty kernel buffer and won’t report stdin again until more is typed. For robust console handling, read() from the descriptor directly and split lines yourself.
select() vs poll()
select() | poll() | |
|---|---|---|
| Descriptor limit | FD_SETSIZE (often 1024) | None beyond process limits |
| Interface | Bit sets, rebuilt every call | Array of structs; revents separate from events |
| Portability | Everywhere, including Winsock | POSIX; Windows has WSAPoll |
| Timeout precision | Microseconds (timeval) | Milliseconds |
Prefer poll() in new Unix code; use select() when you need maximum portability or are maintaining code that already uses it.
Key takeaways
select()watches read, write and exception sets and overwrites them with the ready descriptors.- Keep a master set, copy it before each call, and pass
max_fd + 1. - Reset the timeout each loop and handle
EINTR. - Respect
FD_SETSIZE; for large or new programs preferpoll()orepoll.
Exercises
- Add a
/kick Noperator command that disconnects the client on fd N. - Rewrite
select_console.cto usepoll()and compare the two versions line by line. - Use the write set: make one client socket non-blocking, queue a large announcement, and send the rest only when
select()says it’s writable.
Quiz
- Why do we copy the master
fd_setbefore eachselect()call? - What value must the first argument of
select()have? - What happens if you
FD_SET()descriptor 2000 on a system whereFD_SETSIZEis 1024?
Show answers
select()overwrites the sets with only the ready descriptors, so the original membership would be lost.- The highest descriptor number in any of the sets, plus one.
- Undefined behaviour: it writes past the end of the
fd_set, typically corrupting nearby memory. Usepoll()for high descriptor numbers.