What you will learn
- Which socket calls block, and why that’s a problem for servers.
- How to make a socket non-blocking with
fcntl()and whatEAGAINmeans. - Three ways to put time limits on network operations.
- A reusable
connect_with_timeout().
Blocking: the default
By default, socket calls block: they put your process to sleep until they can do their job.
| Call | Blocks until |
|---|---|
accept() | A connection is waiting |
connect() | The handshake completes or fails (can take over a minute) |
recv() / recvfrom() | At least one byte (or a datagram) is available |
send() | There’s room in the send buffer for some of the data |
Blocking is convenient: the code reads top to bottom. But a single-threaded server blocked in recv() on one client can’t accept() anybody else. There are three ways out: one process or thread per client (lesson 10), non-blocking sockets plus a readiness API (lessons 13–14), or both.
Non-blocking mode
Set the O_NONBLOCK flag with fcntl(). Read the current flags first so you don’t clear others:
#include <fcntl.h>
int set_nonblocking(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
return -1;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
(On Linux you can also create the socket non-blocking: socket(family, SOCK_STREAM | SOCK_NONBLOCK, 0).)
Now calls that would have slept return immediately with -1 and errno set to EAGAIN or EWOULDBLOCK (check both; they’re the same value on Linux but not everywhere):
ssize_t n = recv(fd, buf, sizeof buf, 0);
if (n == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
/* nothing to read right now - do something else and try later */
}
Don’t busy-loop on a non-blocking socket, calling recv() thousands of times a second; that burns a whole CPU core. Pair non-blocking sockets with poll() or select(), which sleep until a socket is ready.
Timeout option 1: SO_RCVTIMEO and SO_SNDTIMEO
The simplest way to bound a blocking recv() or send():
struct timeval tv = { .tv_sec = 5, .tv_usec = 0 };
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
After that, a recv() that waits more than 5 seconds fails with EAGAIN/EWOULDBLOCK. The timeout applies to every later call on that socket. It works for UDP request-reply retries too.
Timeout option 2: wait with poll() first
Call poll() (or select()) with a timeout on the single socket, then recv() only if it reported data:
struct pollfd p = { .fd = fd, .events = POLLIN };
int ready = poll(&p, 1, 3000); /* milliseconds */
if (ready == 0)
puts("timed out");
else if (ready == 1)
n = recv(fd, buf, sizeof buf, 0); /* won't block now */
This style extends naturally to waiting on many sockets, which is the topic of the next lesson.
Timeout option 3: connect() with a deadline
SO_SNDTIMEO affects connect() on Linux, but the portable approach is: switch to non-blocking, start the connect, wait for writability with a timeout, then read the final result from SO_ERROR.
/* connect_timeout.c - connect() with a deadline, and recv() with a timeout.
* Usage: ./connect_timeout example.com 80 2000 */
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <netdb.h>
/* Returns 0 when connected, -1 on error or timeout (errno says which). */
static int connect_with_timeout(int fd, const struct sockaddr *addr,
socklen_t len, int timeout_ms)
{
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
return -1;
int rc = connect(fd, addr, len);
if (rc == -1 && errno != EINPROGRESS)
return -1;
if (rc == -1) { /* handshake in progress: wait for it */
struct pollfd p = { .fd = fd, .events = POLLOUT };
rc = poll(&p, 1, timeout_ms);
if (rc == 0) {
errno = ETIMEDOUT;
return -1;
}
if (rc == -1)
return -1;
int err = 0;
socklen_t err_len = sizeof err;
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
if (err != 0) {
errno = err; /* e.g. ECONNREFUSED */
return -1;
}
}
return fcntl(fd, F_SETFL, flags); /* back to blocking mode */
}
int main(int argc, char *argv[])
{
if (argc != 4) {
fprintf(stderr, "usage: %s host port timeout_ms\n", argv[0]);
return 1;
}
int timeout_ms = atoi(argv[3]);
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int rc = getaddrinfo(argv[1], argv[2], &hints, &res);
if (rc != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
return 1;
}
int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (fd == -1 || connect_with_timeout(fd, res->ai_addr, res->ai_addrlen, timeout_ms) == -1) {
perror("connect");
freeaddrinfo(res);
return 2;
}
freeaddrinfo(res);
printf("connected\n");
/* Give every later recv() a 2-second limit. */
struct timeval tv = { .tv_sec = 2, .tv_usec = 0 };
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
char buf[256];
ssize_t n = recv(fd, buf, sizeof buf, 0);
if (n == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))
printf("server said nothing for 2 seconds\n");
else if (n >= 0)
printf("got %zd bytes\n", n);
else
perror("recv");
close(fd);
return 0;
}
Why each step matters:
- A non-blocking
connect()returns -1 withEINPROGRESSstraight away while the handshake continues in the background. - When the handshake finishes, successfully or not, the socket becomes writable, so we wait for
POLLOUT. - Writable doesn’t mean success.
getsockopt(SO_ERROR)returns the real outcome, for exampleECONNREFUSED. - Finally we restore the original flags so the rest of the program can use ordinary blocking calls.
Try ./connect_timeout localhost 1 1000 (nothing listens on port 1, so it’s refused at once) and an unroutable address to see the timeout path.
Signals and EINTR
A blocking call can also return early with EINTR if a signal handler ran. Either install handlers with SA_RESTART (as the shout server does), or treat EINTR as “try again” in your loops. select() and poll() are never restarted automatically, so always handle EINTR around them.
Key takeaways
- Blocking calls are simple but stall a single-threaded server.
fcntl(F_SETFL, flags | O_NONBLOCK)makes calls returnEAGAIN/EWOULDBLOCKinstead of sleeping.- Bound waits with
SO_RCVTIMEO, withpoll()before reading, or with the non-blocking connect pattern. - Handle
EINTR; never spin on a non-blocking socket without a readiness call.
Exercises
- Add a 10-second idle timeout to the shout server’s
serve_client()usingSO_RCVTIMEO, and sendbye (idle)before closing. - Turn
connect_with_timeout()into a client that tries everygetaddrinfo()result with a 2-second limit each. - Write a UDP “ping” client: send a datagram, wait 500 ms for an echo with
poll(), and print the round-trip time or “lost”.
Quiz
- What does
recv()return on a non-blocking socket with no data waiting? - After a non-blocking
connect()returnsEINPROGRESS, how do you learn whether it succeeded? - Why is calling
recv()in a tight loop on a non-blocking socket a bad idea?
Show answers
- -1, with
errnoset toEAGAINorEWOULDBLOCK. - Wait until the socket is writable (
poll()withPOLLOUTorselect()write set), then readSO_ERRORwithgetsockopt(); 0 means connected. - It wastes a full CPU core spinning. Use
poll()/select()to sleep until the socket is ready.