
Recall first from The three fd tables and dup
- An fd is an index into a per-process table; the offset and status flags live in the open file description behind it.
- dup, dup2, dup3 and fork make descriptors share one open file description; a second open() of the same file does not.
- dup2 closes the target descriptor and copies it in one atomic step; dup3 adds flags such as O_CLOEXEC.
fcntl: one call, many jobs
3 min readThe previous lesson showed that status flags live in the shared open file description behind a descriptor. This lesson answers what fcntl can do to those flags and to the descriptor itself, and how an unmarked descriptor leaks past exec.
#include <fcntl.h>
int fcntl(int fd, int cmd, ...);
The most common job is reading and changing the open file status flags, the ones you passed to open. F_GETFL returns them; F_SETFL writes them back. Because the flags live in the open file description, a change through one duplicated descriptor is visible through all of them. The safe pattern is read, modify, write:
int flags = fcntl(fd, F_GETFL);
if (flags == -1) { perror("fcntl F_GETFL"); exit(1); }
if (fcntl(fd, F_SETFL, flags | O_APPEND) == -1) {
perror("fcntl F_SETFL");
exit(1);
}
This matters most for descriptors you did not open yourself: the three standard descriptors, or the ends returned by pipe() and socket(). You cannot pass flags to those calls, so fcntl is the only way to add O_NONBLOCK or O_APPEND afterwards.
Two details trip people up. First, the access mode is not a single bit: O_RDONLY is 0, O_WRONLY is 1, O_RDWR is 2. To test it, mask with O_ACCMODE and compare: if ((flags & O_ACCMODE) == O_WRONLY). Second, F_SETFL can only change some flags. On Linux these are O_APPEND, O_NONBLOCK, O_NOATIME, O_ASYNC and O_DIRECT. Attempts to change the access mode or other flags are ignored, not reported as errors.
You cannot turn a read-only descriptor into a writable one with F_SETFL. The access mode is fixed at open time. If you need write access, open the file again with the mode you need.
F_GETFD and F_SETFD read and set the descriptor flags, which today means only FD_CLOEXEC, the close-on-exec flag covered in the next section. Note the pairing: F_GETFL/F_SETFL act on the shared open file description; F_GETFD/F_SETFD act on the private fd table entry.
For duplication, fcntl(oldfd, F_DUPFD, start) returns the lowest free descriptor greater than or equal to start. It is dup with a floor, useful when you want to keep low numbers free. F_DUPFD_CLOEXEC does the same and sets close-on-exec on the new descriptor in the same step.
Finally, F_GETOWN and F_SETOWN get and set the process or process group that receives SIGIO and SIGURG for this descriptor. A negative value means a process group. Combined with O_ASYNC, this is signal-driven I/O: the kernel sends SIGIO when input arrives on a terminal, pipe or socket. Regular files never generate these signals. The newer F_SETOWN_EX and F_GETOWN_EX take a small structure and can target a single thread, removing the ambiguity between a PID and a process group ID. You will use this machinery again in the event-loop lessons.
Close-on-exec: stopping fd leaks at exec
4 min readWhen a process calls execve, the system call that loads a new program into the process, the kernel replaces the program but keeps the fd table, except for descriptors marked with a per-descriptor flag, FD_CLOEXEC, that makes the kernel close the descriptor automatically when an exec succeeds. This default is deliberate: the shell's redirections from the previous section only work because the descriptors survive exec. A pipe you built for a child only works because the child inherits its ends.
But every other open descriptor survives too. A log file, a database, a listening socket: the new program inherits them all, whether it wants them or not. On a long-running embedded system this is a real failure mode. A supervisor that opens a config file and then execs a helper hands the helper an open config fd; the helper execs something else; the chain grows. The file may stay unlinked-but-open, its space never freed, and a privileged descriptor may land in a less privileged program.
Reproduce the leak in three lines of substance:
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
open("/home/learner/secret.log", O_WRONLY | O_CREAT | O_APPEND, 0600);
execlp("ls", "ls", "-l", "/proc/self/fd", (char *)NULL);
return 1; /* reached only if exec failed */
}
ls lists its own descriptors, which are the ones our program handed over. Among the standard descriptors you will see a line like this (typical output, yours will differ):
3 -> /home/learner/secret.log
The fix is to mark the descriptor. The modern way is at creation time, with O_CLOEXEC in the open flags:
int fd = open("/home/learner/secret.log",
O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0600);
Now exec closes it, and the listing shows no secret.log, only the standard descriptors plus ls's own temporary directory handle. The older way is a second call after open:
int flags = fcntl(fd, F_GETFD);
if (flags == -1) { perror("fcntl F_GETFD"); exit(1); }
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
perror("fcntl F_SETFD");
exit(1);
}
Both work in a single-threaded program. In a threaded one, only the atomic forms are safe, as the deep block below explains. For duplicates, remember that dup, dup2 and F_DUPFD always clear close-on-exec on the new descriptor. If the duplicate must also be marked, use dup3 with O_CLOEXEC or F_DUPFD_CLOEXEC.
The flag's journey through process creation is easy to confuse, so pin it down. fork copies the flag as-is into the child; the descriptor stays open in both. exec closes exactly the descriptors whose flag is set. A descriptor without the flag survives any number of execs. One legitimate exception to marking everything: systemd socket activation hands a service pre-opened listening descriptors that must survive exec, so those are deliberately left unmarked.
Going deeperWhy the atomic forms exist
Between open() and fcntl(F_SETFD) there is a window. In a multithreaded program, another thread can fork and exec inside that window, and the child inherits the unmarked descriptor. No amount of care in your own thread closes it. The kernel added O_CLOEXEC in Linux 2.6.23, F_DUPFD_CLOEXEC in 2.6.24, and dup3 in 2.6.27 precisely to make marking atomic with creation. The rule in modern code: mark at creation, never as an afterthought. The same reasoning applies to accept4 with SOCK_CLOEXEC, pipe2 with O_CLOEXEC, and socket with SOCK_CLOEXEC, which you will meet in the sockets lessons.
Nonblocking I/O and files beyond 2 GB
4 min readO_NONBLOCK has two effects. At open time, it stops the open itself from waiting: this matters for FIFOs, named pipes that exist as files in the filesystem, where a normal open blocks until the other end appears. After open, it changes I/O: a read with no data available, or a write to a full buffer, returns -1 with errno EAGAIN instead of sleeping. On Linux, EAGAIN and EWOULDBLOCK are the same value, so checking either works; portable code checks both.
Regular files are the exception people misread. A read from a regular file is served from the page cache when possible, and when the data is not cached the kernel waits for the storage. That wait happens regardless of O_NONBLOCK, and it is uninterruptible. So O_NONBLOCK does not make regular-file I/O instant; it is effectively ignored there. Its historical effect on regular files was tied to mandatory locking, which no longer exists on current kernels. Where the flag earns its keep is pipes, sockets, terminals and device files:
int p[2];
if (pipe(p) == -1) { perror("pipe"); exit(1); }
int fl = fcntl(p[0], F_GETFL);
if (fl == -1 || fcntl(p[0], F_SETFL, fl | O_NONBLOCK) == -1) {
perror("fcntl");
exit(1);
}
char buf[64];
ssize_t n = read(p[0], buf, sizeof buf); /* -1, errno EAGAIN: pipe empty */
pipe() gives you no chance to pass flags, so F_SETFL is the standard route. In nonblocking mode a read or write may also transfer fewer bytes than requested, exactly like the short counts of the previous lesson; your loops must handle both. For FIFOs, open(path, O_RDONLY | O_NONBLOCK) succeeds immediately even with no writer, while open(path, O_WRONLY | O_NONBLOCK) fails with ENXIO if no reader has the FIFO open.
The second topic is size. The offset type off_t is signed, because -1 marks errors. On a 32-bit system a signed long is 32 bits, so offsets stop at 2^31 - 1 bytes, just under 2 GB. Disks outgrew that long ago. The Large File Summit of 1996 defined the fix, and Linux has supported it on 32-bit systems since kernel 2.4.
1compile with 64-bit offsets
Define _FILE_OFFSET_BITS to 64 before any header, or on the command line:
gcc -D_FILE_OFFSET_BITS=64 -o bigtool bigtool.c
The headers then redirect off_t to a 64-bit type and turn open, lseek, stat and friends into their 64-bit variants transparently. Your source does not change. Without it, a 32-bit program that stats a file over 2 GB fails with EOVERFLOW. The older transitional API, open64 and lseek64 with _LARGEFILE64_SOURCE, still exists but is obsolete; do not write new code against it.
2print offsets correctly
With the macro set, off_t can be wider than long, so the usual cast-to-long trick is not enough. Cast to long long and use %lld, as the dup example above already does. Also make sure every module that passes off_t around was compiled with the same setting, or the types will not match across the boundary.
On 64-bit systems, including your Ubuntu host and a 64-bit Raspberry Pi, off_t is already 64 bits and none of this is needed. It matters on 32-bit ARM boards, which are still common in products. Two limits sit below the API anyway: FAT32, often used on SD cards, caps a single file at 4 GiB minus one byte, and NFSv2 caps files at 2 GB regardless of your compile flags.
On a 32-bit Cortex-A board running a glibc Buildroot image, add -D_FILE_OFFSET_BITS=64 to the package's CFLAGS or a logger will silently fail on a 2 GB file. If the image uses musl instead of glibc, off_t is always 64 bits and the macro is a no-op; musl never had a 32-bit off_t. Know which libc your toolchain targets before you debug a size problem.
Key takeaways
- fcntl reads and sets status flags with F_GETFL/F_SETFL and the per-descriptor close-on-exec flag with F_GETFD/F_SETFD.
- O_CLOEXEC, dup3 and F_DUPFD_CLOEXEC mark descriptors atomically; open-then-fcntl has a race in threaded programs.
- O_NONBLOCK changes pipes, sockets and FIFOs, not regular files; 32-bit systems need _FILE_OFFSET_BITS=64 for files over 2 GB.
- exec keeps every open descriptor by default; only descriptors marked close-on-exec are closed, which is exactly why shell redirection works.
Reflect
- Explain to a colleague, in two sentences: read and change open file status flags and descriptor flags with fcntl, and set close-on-exec atomically.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.