Course contentsShow
← C
Lesson 1098 of 1,21915. Systems ProgrammingFree lesson

Non-blocking I/O basics

Non-blocking I/O basics

What you'll learn: How to tell the operating system to return control to your program immediately even if a file or socket isn't ready to send or receive data.

The Waiting Room Problem

By default, I/O operations in C are "blocking." When you call read(), your program hits a pause button. If you are reading from a keyboard and the user hasn't typed anything, or reading from a network socket and no data has arrived, your program simply sits there doing nothing. It stays suspended until the operating system can fulfill the request.

Imagine a waiter who stands at your table and refuses to leave until you decide what to order. They can't check on other tables or refill water; they are "blocked" by your indecision.

Going Non-blocking

Non-blocking I/O changes this behavior. Instead of waiting, the function returns immediately. If data is ready, you get it. If not, the function returns an error code telling you, "I have nothing for you right now; try again later."

To do this, we use the fcntl() (file control) function to add the O_NONBLOCK flag to a file descriptor.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int main() {
    char buf[10];
    
    // Set STDIN (0) to non-blocking mode
    int flags = fcntl(0, F_GETFL, 0);
    fcntl(0, F_SETFL, flags | O_NONBLOCK);

    printf("Try typing something quickly... (Waiting 5 seconds)\n");

    for (int i = 0; i < 5; i++) {
        ssize_t bytes = read(0, buf, sizeof(buf) - 1);

        if (bytes > 0) {
            buf[bytes] = '\0';
            printf("Got data: %s", buf);
        } else if (errno == EAGAIN || errno == EWOULDBLOCK) {
            printf("No data yet, doing other work...\n");
        }
        
        sleep(1);
    }

    return 0;
}

How it works

In the code above, read() no longer halts the program. Instead, we check errno. If it equals EAGAIN, it means the resource is temporarily unavailable. This allows your program to perform other calculations, update a UI, or check other file descriptors while waiting for input.

This is the foundation of high-performance servers that handle thousands of connections simultaneously without needing a separate thread for every single user.

Key takeaway

Non-blocking I/O allows your program to remain responsive by forcing read() and write() to return immediately with a "try again" status instead of pausing execution.