Skip to content
systemcoding.dev
Networking

Blocking vs Non-Blocking I/O Explained

Learn what blocking and non-blocking I/O mean for sockets on POSIX, what EAGAIN tells you, and why servers with many clients switch to non-blocking mode.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the C, Linux and Rust logos.

A server that calls read() on a socket and then does nothing else until data shows up is easy to write and easy to break. One slow client holds the thread, and every other client waits behind it. The difference between blocking and non-blocking I/O is the difference between a call that waits and a call that answers immediately, and nearly every network server design follows from which of the two you choose. This post defines both terms, shows the same read in each mode on Linux 6.12 with glibc 2.40, and explains the one error code, EAGAIN, that makes non-blocking code work. It is the starting point for the I/O multiplexing guide that builds on it.

Two words, defined

A file descriptor is a small integer the kernel gives you for an open file, pipe or socket. An I/O call is a system call such as read, write, accept or connect that moves data or connections through a descriptor.

Blocking means the call does not return until it can make progress. If you call read() on a socket with no data waiting, the kernel puts your thread to sleep. When data arrives, the kernel wakes the thread and the call returns the bytes. From your program's view, the call simply took a long time.

Non-blocking means the call returns at once, whether or not it could make progress. If no data is waiting, read() returns -1 and sets errno to EAGAIN (or its synonym EWOULDBLOCK, which on Linux is the same value). The call has told you "nothing right now"; it has not failed.

Sockets are blocking by default. The POSIX specification describes this in its pages for read and O_NONBLOCK, and the Linux socket(7) and fcntl(2) man pages describe the Linux behavior.

Blocking mode in a complete program

Here is a server that handles one client at a time, in blocking mode. It reads whatever arrives and echoes it back.

blocking_echo.cc
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

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(7000),
        .sin_addr.s_addr = htonl(INADDR_LOOPBACK),
    };
    bind(srv, (struct sockaddr *)&a, sizeof a);
    listen(srv, 16);

    for (;;) {
        int c = accept(srv, NULL, NULL);      /* sleeps until a client connects */
        char buf[512];
        ssize_t n;
        while ((n = read(c, buf, sizeof buf)) > 0)   /* sleeps until data */
            write(c, buf, (size_t)n);
        close(c);
    }
}

Every call that can wait does wait. accept sleeps until someone connects, and read sleeps until that client sends something. While the inner loop waits for client A, client B can connect (the kernel completes the handshake and queues it) but nobody calls accept for it. B's connection sits in the listen backlog until A closes. That is the cost of blocking mode: one thread can only wait for one thing.

You can fix that with a thread or process per client, which is the classic approach and still reasonable for a small number of connections. Each thread blocks independently, and the scheduler does the multiplexing. The price is memory for each stack and the cost of context switches, which grows with the client count.

Non-blocking mode in a complete program

The alternative is one thread that never sleeps inside an I/O call. You mark the descriptor non-blocking, and each call either does the work or reports that it would have waited.

nonblocking_read.cc
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void)
{
    int sv[2];
    socketpair(AF_UNIX, SOCK_STREAM, 0, sv);

    int flags = fcntl(sv[0], F_GETFL, 0);
    fcntl(sv[0], F_SETFL, flags | O_NONBLOCK);

    char buf[64];
    ssize_t n = read(sv[0], buf, sizeof buf);
    if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
        puts("read: no data yet (EAGAIN)");

    write(sv[1], "hello", 5);

    n = read(sv[0], buf, sizeof buf);
    printf("read: %zd bytes: %.*s\n", n, (int)n, buf);
    return 0;
}

A socketpair gives two connected sockets inside one process, so the program needs no network. The first read finds nothing and returns at once. After the other end writes five bytes, the second read succeeds.

Text
read: no data yet (EAGAIN)
read: 5 bytes: hello

If the descriptor were blocking, the first read would never return, because no one else in the program would ever write. That is the difference in one line.

What the return values mean

A non-blocking call has three outcomes, and a correct program handles all three:

ReturnMeaningWhat to do
a positive countthat many bytes were transferreduse them; there may be more
0 from readthe peer closed the connectionclose your end
-1 with EAGAINthe call would have blockedstop, and retry when the descriptor is ready
-1 with another errora real failurehandle or close

Two details trip beginners. First, a positive count may be smaller than what you asked for, on both read and write. A write of 100,000 bytes to a non-blocking socket may accept 65,536 and return that, leaving you to send the rest later. Second, EAGAIN is not retried in a tight loop. Looping on it burns a whole CPU core asking "is it ready yet?", which is called busy waiting.

Where readiness notification fits

The missing piece is how to know when to retry. That is the job of select, poll, epoll on Linux and kqueue on BSD and macOS. You hand the kernel a set of descriptors and sleep in one call until any of them is ready, then do the non-blocking I/O that now cannot block. The guide linked above covers all four. The pairing is the pattern to remember: a readiness call that may block, plus I/O calls that never do.

Blocking versus non-blocking, side by side

BlockingNon-blocking
A call with no datasleepsreturns EAGAIN
Program structurestraight-line, one wait per threadevent loop with state per connection
Concurrencythreads or processesone thread can serve many sockets
Hard partsthread count and context switchespartial I/O and per-connection state machines
Good fitsmall client counts, simple toolsservers with thousands of idle connections

Non-blocking code is harder to write because the call stack no longer remembers where you were. A blocking read can sit in the middle of a function and the stack holds the half-parsed request. A non-blocking handler has to save that parse state in a structure and resume it on the next readiness event.

When blocking is the right choice

Do not reach for non-blocking mode by reflex. A command-line tool that talks to one server, a batch job that reads one file, or a service with a few dozen clients is simpler and just as fast with blocking calls. Blocking I/O is also what you want for regular files on local disks, because O_NONBLOCK has no effect on them: the kernel reads from the page cache or the disk and the call still takes as long as it takes. For disk I/O that must not stall a thread, use a thread pool or io_uring, covered later in this series.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.