Prevent FD Leaks into Child Processes with O_CLOEXEC
Open files with O_CLOEXEC so exec closes them automatically. Shows the leak into a child, the race with fcntl, and the flags for socket, pipe2 and dup3.

A descriptor you open in a program does not stay private. By default it survives exec(), so every program you launch inherits it, including ones you did not write and never meant to trust with your log file, your database socket or your private key. The fix is one flag. Pass O_CLOEXEC when you open the descriptor, and the kernel closes it automatically during exec(). This post shows the leak first so you can see it, then the fix, then the one reason the flag has to be set at creation instead of afterwards. It also lists the matching flags for sockets, pipes and duplicates. It assumes Linux 6.12 and glibc 2.40, and that you know what a file descriptor is.
How descriptors cross exec
When a process calls fork(), the child gets copies of every descriptor. When the child then calls exec() to run a new program, the new program image replaces the old one but the process, and its descriptor table, stay. POSIX says descriptors remain open across exec() unless the close-on-exec flag is set on them. That default is what makes shell redirection work, because the shell sets up descriptor 1 before exec(). It is also what leaks everything else.
The leak is easy to see. This program opens a file, then runs ls -l /proc/self/fd as a child, and that command lists what it inherited:
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int secret = open("/etc/hostname", O_RDONLY); /* no O_CLOEXEC */
printf("parent opened descriptor %d\n", secret);
fflush(stdout);
if (fork() == 0) {
execlp("ls", "ls", "-l", "/proc/self/fd", (char *)NULL);
_exit(127);
}
wait(NULL);
return 0;
}Built with gcc -Wall -o leak leak.c, the run prints something like:
parent opened descriptor 3
total 0
lrwx------ 1 dev dev 64 Nov 23 10:30 0 -> /dev/pts/2
lrwx------ 1 dev dev 64 Nov 23 10:30 1 -> /dev/pts/2
lrwx------ 1 dev dev 64 Nov 23 10:30 2 -> /dev/pts/2
lr-x------ 1 dev dev 64 Nov 23 10:30 3 -> /etc/hostname
lr-x------ 1 dev dev 64 Nov 23 10:30 4 -> /proc/4502/fdDescriptor 3, the file the parent opened, is open inside ls. The ls command never asked for it and cannot know why it is there. Descriptor 4 is ls reading its own listing. The timestamps and process id differ on every run.
A harmless file hides how serious this can get. Replace /etc/hostname with a listening socket, a database connection or a file holding secrets, and every child process becomes a holder of it. A leaked listening socket keeps a port bound after the parent exits. A leaked pipe write end stops a reader from ever seeing end of file, because the pipe stays open while any copy of the write end exists, and that is one of the most common causes of a hang in programs that spawn helpers.
The fix: ask for close-on-exec at creation
Add O_CLOEXEC to the flags in open(). POSIX added this flag in the 2008 edition, and Linux has supported it since 2.6.23:
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int secret = open("/etc/hostname", O_RDONLY | O_CLOEXEC);
printf("parent opened descriptor %d\n", secret);
fflush(stdout);
if (fork() == 0) {
execlp("ls", "ls", "-l", "/proc/self/fd", (char *)NULL);
_exit(127);
}
wait(NULL);
return 0;
}parent opened descriptor 3
total 0
lrwx------ 1 dev dev 64 Nov 23 10:31 0 -> /dev/pts/2
lrwx------ 1 dev dev 64 Nov 23 10:31 1 -> /dev/pts/2
lrwx------ 1 dev dev 64 Nov 23 10:31 2 -> /dev/pts/2
lr-x------ 1 dev dev 64 Nov 23 10:31 3 -> /proc/4510/fdThe inherited file is gone. What remains at 3 is ls reading its own directory, which took the lowest free number once the leaked descriptor was closed. The flag does not close the descriptor in the parent. It only tells the kernel to close it at the moment exec() succeeds, so the parent can keep using it freely.
Why fcntl afterwards is not enough
You can set the same flag after the fact with fcntl(fd, F_SETFD, FD_CLOEXEC), and old code does:
int fd = open("/etc/hostname", O_RDONLY);
fcntl(fd, F_SETFD, FD_CLOEXEC);That works in a single-threaded program, and fails in a threaded one. Between the open() and the fcntl() another thread can call fork() and exec(), and the child inherits the descriptor in the window where the flag is not yet set. The two calls are not atomic. This race is the reason O_CLOEXEC exists: the flag is applied inside open() itself, with no gap. In a library that may be used by threaded programs, the fcntl form is a latent bug.
The same flag for every call that makes a descriptor
Each way of creating a descriptor has its own spelling for close-on-exec, and each exists for the same atomicity reason:
| Call | Close-on-exec form | Notes |
|---|---|---|
open() / openat() | O_CLOEXEC | POSIX 2008 |
socket() | SOCK_CLOEXEC in the type argument | Linux 2.6.27 |
accept4() | SOCK_CLOEXEC in the flags | accept() has no flags; use accept4() |
pipe2() | O_CLOEXEC | pipe() has no flags |
dup3() | O_CLOEXEC | dup2() has no flags |
fcntl(F_DUPFD_CLOEXEC) | built in | POSIX 2008 |
epoll_create1() | EPOLL_CLOEXEC | epoll_create() has none |
eventfd(), timerfd_create(), signalfd() | EFD_CLOEXEC, TFD_CLOEXEC, SFD_CLOEXEC | Linux |
A pipe shows the pattern clearly:
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int fds[2];
if (pipe2(fds, O_CLOEXEC) < 0) {
perror("pipe2");
return 1;
}
printf("read end %d, write end %d\n", fds[0], fds[1]);
int flags = fcntl(fds[0], F_GETFD);
printf("FD_CLOEXEC on read end: %s\n", (flags & FD_CLOEXEC) ? "set" : "clear");
close(fds[0]);
close(fds[1]);
return 0;
}read end 3, write end 4
FD_CLOEXEC on read end: setpipe2() needs _GNU_SOURCE with glibc, as does accept4(). The query in the example uses F_GETFD, which reports the descriptor flags, not the status flags.
Choosing the default
Make O_CLOEXEC the default for every descriptor your program creates, and remove it deliberately on the few you want a child to inherit. Those few are usually descriptors 0, 1 and 2, plus anything a launcher passes on purpose, such as a socket handed to a worker or a pipe for a status channel. To pass a descriptor on purpose after creating it with the flag, clear it in the child between fork() and exec() with fcntl(fd, F_SETFD, 0). That runs in a single-threaded child, so the race does not apply.
Streams and libraries
The C library has its own spelling. With glibc, fopen() accepts the mode letter e, so fopen("data.csv", "re") opens for reading with O_CLOEXEC set. It is a glibc extension that POSIX later adopted in the 2024 edition, so older toolchains may not recognize it, and the portable fallback is open() with O_CLOEXEC followed by fdopen().
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int fd = open("/etc/hostname", O_RDONLY | O_CLOEXEC);
if (fd < 0) { perror("open"); return 1; }
FILE *f = fdopen(fd, "r"); /* the flag stays on the descriptor */
char line[128];
if (fgets(line, sizeof line, f))
printf("hostname: %s", line);
fclose(f); /* closes fd as well */
return 0;
}hostname: build-hostThe hostname shown is an example. What matters is that fdopen() wraps the descriptor without clearing its flag, and fclose() closes both the stream and the descriptor, so there is no second close() to forget.
The same discipline applies to library code you write. A function that returns a descriptor to its caller should create it with the flag already set, since the caller has no way to close the window the fcntl form leaves open. Libraries that spawn processes, such as a popen() replacement, are the places where an unmarked descriptor does the most damage, because they run exec() on your behalf at a moment you do not control.
Auditing what a program leaks
To check an existing program, run it under strace and filter for the calls that create descriptors. Anything that returns a descriptor without a close-on-exec flag is a candidate:
strace -f -e trace=openat,socket,pipe2,dup3 ./server 2>&1 | headopenat(AT_FDCWD, "/etc/app.conf", O_RDONLY) = 3
socket(AF_INET, SOCK_STREAM, IPPROTO_IP) = 4
openat(AT_FDCWD, "/var/log/app.log", O_WRONLY|O_CREAT|O_APPEND|O_CLOEXEC, 0644) = 5The first two lines show the leak: neither O_CLOEXEC nor SOCK_CLOEXEC appears, so a child launched later inherits descriptors 3 and 4. The third line is correct. The trace shows what the program asked the kernel for, which is more reliable than reading the source when a library does the opening. A second check works at runtime, from the child's side: run ls -l /proc/self/fd as the child, as in the first example, and any target that is not a terminal or a pipe you passed on purpose is a leak.
When this does not help
O_CLOEXEC only acts at exec(). A child created with fork() and no exec() still holds every descriptor, so a forking server that never execs needs to close the ones it does not want in the child. The flag also does nothing for descriptors you open before the flag existed in a library you do not control; for those, Linux 5.9 and later offers close_range() to close a numeric span in the child, and the close-all-above-a-number post in this cluster shows it. And nothing here protects against code that deliberately re-opens a path, because a path is not a descriptor.


