The close-on-exec flag
What you'll learn: How to prevent sensitive file descriptors from "leaking" into child processes when running new programs.
The problem: The "sticky" file descriptor
In Linux and Unix systems, when you use fork(), the child process inherits every single file descriptor the parent had open. If the child then calls execve() to transform into a completely different program (like running ls or a custom script), those file descriptors stay open.
Imagine you are a bank manager (the parent process) holding a master key (a file descriptor) to a vault. You hire a temporary contractor (the child process) to clean the lobby. If you don't explicitly take that key away before they start working, that contractor—and any tools they use—now has access to your vault. In programming, this "leak" is a security risk and can lead to resource exhaustion.
The solution: FD_CLOEXEC
Instead of manually closing every file before calling exec(), you can tag a file descriptor with the Close-on-Exec flag. This tells the kernel: "If this process ever performs an exec, close this specific file automatically right before the new program starts."
You can set this flag when you first open the file using the O_CLOEXEC flag, or later using fcntl.
Seeing it in action
Here is how you protect a sensitive file so it doesn't leak into a child process:
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
// 1. Open a file with the Close-on-Exec flag enabled
int fd = open("secret_data.txt", O_RDONLY | O_CLOEXEC);
if (fd == -1) {
perror("Open failed");
return 1;
}
// 2. We fork and exec a new program (e.g., /bin/ls)
// Because of O_CLOEXEC, "secret_data.txt" will NOT be
// available to the 'ls' program. It closes automatically.
char *args[] = {"/bin/ls", NULL};
execv(args[0], args);
return 0;
}
Why this matters
Modern systems use O_CLOEXEC by default whenever possible. If you are writing a library that opens a database connection or a log file, you don't want a user's random system("clear") call to inherit your private database handle. By using the close-on-exec flag, you ensure that resources stay exactly where they belong: in the process that actually needs them.
Key takeaway
The FD_CLOEXEC flag ensures that a file descriptor is automatically closed when a process calls exec, preventing sensitive data leaks to child programs.