Make a Socket Non-Blocking with fcntl and O_NONBLOCK
Switch a socket to non-blocking mode with fcntl and O_NONBLOCK, or set it atomically with SOCK_NONBLOCK and accept4, and learn the flag mistakes that bite.

Before a socket can take part in an event loop it has to stop blocking, and POSIX gives you one small, widely copied way to do it: read the descriptor's status flags with fcntl, add O_NONBLOCK, and write them back. Three lines, and nearly everyone gets one detail of them wrong at least once. This post shows the pattern, the shorter Linux-only forms (SOCK_NONBLOCK and accept4), and the mistakes that leave a socket silently blocking. If the terms are new, read blocking vs non-blocking I/O first. Examples target Linux 6.12 and glibc 2.40.
The portable recipe
fcntl(fd, F_GETFL) returns the file status flags of a descriptor, and fcntl(fd, F_SETFL, flags) replaces them. O_NONBLOCK is one bit among those flags, so you must read first and OR the bit in. Writing F_SETFL, O_NONBLOCK alone would clear the others, including O_APPEND and, on some systems, access-mode information that the kernel then ignores.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
int set_nonblocking(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0)
return -1;
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
return -1;
return 0;
}
int is_nonblocking(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
return flags >= 0 && (flags & O_NONBLOCK) != 0;
}Both calls can fail, with EBADF for a closed descriptor being the usual cause, so check them. The functions come from the POSIX fcntl specification and the Linux fcntl(2) man page.
Here is the function in use on a connected pair of sockets, with the result printed so you can see the flag change:
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
int set_nonblocking(int fd);
int is_nonblocking(int fd);
int main(void)
{
int sv[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0)
return 1;
printf("before: %d\n", is_nonblocking(sv[0]));
set_nonblocking(sv[0]);
printf("after: %d\n", is_nonblocking(sv[0]));
printf("peer: %d\n", is_nonblocking(sv[1]));
close(sv[0]);
close(sv[1]);
return 0;
}before: 0
after: 1
peer: 0The flag belongs to the open file description behind the descriptor, so it affects only that socket. The other end of the pair is untouched, which is why peer stays 0.
Doing it in one step on Linux
The recipe has a gap: between socket() and fcntl() the descriptor exists in blocking mode. In a single-threaded program that does not matter. In a multithreaded one a fork or another thread can see it half-configured. Linux closes the gap with flags that apply at creation time.
socket(2) accepts SOCK_NONBLOCK (and SOCK_CLOEXEC) ORed into the type argument:
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/socket.h>
int main(void)
{
int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0) {
perror("socket");
return 1;
}
puts("created non-blocking socket");
return 0;
}created non-blocking socketThe same two flags work for accept4(2), which Linux added in 2.6.28 and glibc exposes with _GNU_SOURCE. This matters more than the socket form, because the socket returned by accept does not inherit O_NONBLOCK from the listening socket on Linux. The accept(2) man page says so: on Linux the new descriptor does not inherit file status flags such as O_NONBLOCK from the listener. BSD-derived systems behave differently, and POSIX leaves it unspecified, so portable code sets the flag explicitly on every accepted socket.
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <sys/socket.h>
int accept_client(int listen_fd)
{
int c = accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (c < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
return -2; /* nobody waiting; try again on readiness */
perror("accept4");
return -1;
}
return c;
}accept4 returns the client already non-blocking and close-on-exec in one atomic call. It is also the only form that does not race with a concurrent fork and exec in another thread, which is the reason SOCK_CLOEXEC exists.
ioctl(FIONBIO) and why fcntl is preferred
You will also meet ioctl(fd, FIONBIO, &on), where on is a nonzero int. It sets or clears non-blocking mode in one call, without a read-modify-write, and it is common in older BSD-style code. Linux supports it. It is not part of POSIX, so fcntl with O_NONBLOCK is the portable choice. On Windows the equivalent is ioctlsocket(FIONBIO), which is a different API entirely.
Mistakes that leave the socket blocking
Overwriting the flags. fcntl(fd, F_SETFL, O_NONBLOCK) works for most descriptors but discards the rest of the flag word. Always read, OR, write.
Setting the flag on the listener and expecting clients to inherit it. On Linux the accepted socket is blocking unless you use accept4 with SOCK_NONBLOCK or set the flag yourself. The symptom is an event loop that works with the first connection of a test and then freezes inside a read on a later client that sent nothing.
**Using F_SETFD instead of F_SETFL.** F_SETFD sets descriptor flags, which only has FD_CLOEXEC. O_NONBLOCK is a file status flag and needs F_SETFL. The call succeeds on some inputs and does nothing useful, so the bug is silent.
**Assuming connect returns at once on a blocking socket.** A non-blocking connect returns -1 with EINPROGRESS while the handshake runs. You then wait for the socket to become writable and read SO_ERROR with getsockopt to learn the result. A blocking connect hides all of that and returns after the handshake.
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void)
{
int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(80) };
inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);
int rc = connect(fd, (struct sockaddr *)&a, sizeof a);
if (rc < 0 && errno != EINPROGRESS) {
perror("connect");
return 1;
}
struct pollfd p = { .fd = fd, .events = POLLOUT };
poll(&p, 1, 2000);
int err = 0;
socklen_t len = sizeof err;
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
printf("connect result: %s\n", err ? strerror(err) : "connected");
close(fd);
return 0;
}On a machine with nothing listening on port 80 of the loopback interface, the connection is refused almost at once, and the program prints:
connect result: Connection refusedIf something is listening, it prints connect result: connected. Either way the program never blocks inside connect.
When not to bother
If a program talks to a single peer and does nothing else while waiting, making the socket non-blocking only adds EAGAIN handling for no gain. Timeouts, the usual reason people reach for it, can be had with SO_RCVTIMEO and SO_SNDTIMEO while keeping straight-line code. Reserve O_NONBLOCK for sockets that live in an event loop.
Checking the flag from the shell
You do not need a debugger to confirm that a descriptor is non-blocking. On Linux, /proc/<pid>/fdinfo/<fd> lists a flags: line in octal, and the O_NONBLOCK bit is 04000 on x86-64 and arm64. A line reading flags: 02004002, for example, has the non-blocking bit set along with O_RDWR and O_CLOEXEC. Reading that file is a quick way to find the one socket in a running server that was never switched over, which is a common cause of a loop that freezes under load. The kernel exposes the same value to fcntl(F_GETFL), so the two views always agree.
Why the flag lives on the file description
The reason O_NONBLOCK affects the peer of a dup or a forked child, and not a separately opened socket, is that it is stored in the open file description, the kernel object that several descriptors can share. If you dup a socket and set the flag through either descriptor, both become non-blocking, because they point at the same description. The same sharing happens across fork. A parent that makes a socket non-blocking after forking a worker therefore changes the worker's behavior too, which has caused real outages in pre-fork servers that assumed each process had its own copy. When several processes share a socket, decide who owns the mode and set it before the fork.
Making the helper safe for production
The three-line recipe is enough for a lesson, but a helper in a real codebase should report why it failed and avoid changing anything when the flag is already set. Skipping the write when the bit is present saves a system call per socket in code that touches every accepted connection, and it keeps the helper idempotent so callers can invoke it without tracking whether an earlier layer already did. Return the negative errno rather than -1 so the caller can log the cause without a second lookup, and never ignore a failure: a socket that stays blocking inside an event loop is a bug that only appears under load.

