Articles

Understanding File Descriptors in Linux: Tables, dup2, and Redirection Explained with C Examples

Ask five developers what a file descriptor is and you will get five answers: “a number”, “a handle”, “a pointer to a file”. All of them are partly right and all of them hide the detail that actually matters. To really understand how file descriptors work in Linux, you have to follow the path from a tiny integer in your process all the way down to the inode on disk, and notice that there are three separate structures in that chain, not one.

This article walks that path step by step, with annotated C code you can compile and run. By the end you will know exactly why two descriptors can share a read/write offset, why close() does not always close the file, and how a shell implements ls > out.txt in about four lines of code.

The short answer: what a file descriptor actually is

A file descriptor (fd) is a small non-negative integer that indexes an array owned by your process. That array is the per-process file descriptor table. Each slot in it points to a kernel object called an open file description, which in turn points to an inode.

So the integer is not the file. It is not even a pointer to the file. It is an index into a table of pointers to kernel structures that describe an act of opening something. That “something” can be a regular file, a pipe, a socket, a terminal, an eventfd, a timerfd, an epoll instance or a pidfd. In Linux, if you can read it, write it or wait on it, it is almost certainly behind a file descriptor.

linux terminal code

The three layers behind every fd

This is the mental model that makes everything else click. When you call open(), the kernel touches three distinct levels:

Level Structure Scope What it stores
1 File descriptor table (struct files_struct) Per process (shared by threads) An array indexed by the fd number; each entry holds a pointer to an open file description plus the FD_CLOEXEC flag
2 Open file description (struct file, the “open file table”) System wide, can be shared by many processes The file offset, access mode (read/write), status flags (O_APPEND, O_NONBLOCK), a reference count, and a pointer to the inode
3 Inode (struct inode, via the dentry cache) System wide, one per file object File type, size, permissions, owner, timestamps, pointers to the actual data blocks

Visually, the chain is simply:

fd (int) --> [per-process fd table] --> [open file description: offset + flags] --> [inode: the actual file]

Almost every confusing fd behaviour comes from one fact: level 1 and level 2 are not the same thing, and duplication can happen at either level.

The three descriptors you already use

fd Constant Usual meaning Shell syntax
0 STDIN_FILENO Standard input < file
1 STDOUT_FILENO Standard output > file
2 STDERR_FILENO Standard error 2> file
3+ (none) The first descriptor your own open() usually returns exec 3<> file

Those three are not magic. They are simply the slots the shell filled in before it executed your program. Nothing stops you from closing fd 1 and reusing the slot for a socket.

Step 1: watching the kernel hand you a number

The lowest unused descriptor rule is written into POSIX: open(), dup(), socket() and friends always return the smallest free slot in your fd table. That rule is the foundation of the classic redirection trick we will see later.

/* fd-basics.c : cc -Wall -o fd-basics fd-basics.c */
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
    /* open() creates a NEW open file description (level 2)
       and puts a pointer to it in the lowest free slot of
       our fd table (level 1). */
    int fd = open("/tmp/fd-demo.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (fd == -1) { perror("open"); return 1; }

    printf("kernel returned fd = %d\n", fd);   /* almost always 3 */

    write(fd, "hello world\n", 12);
    printf("offset is now %ld\n", (long) lseek(fd, 0, SEEK_CUR)); /* 12 */

    close(fd);   /* frees slot 3; refcount of the description drops to 0 */
    return 0;
}

Run it and the output is fd = 3, because 0, 1 and 2 were already taken by the shell. The offset of 12 lives in the open file description, not in the inode and not in the integer.

linux terminal code

Step 2: dup2 and why two descriptors can share an offset

There are two completely different ways to end up with two descriptors pointing at the same file, and they behave differently. This is the single most important distinction in understanding how file descriptors work in Linux.

Case A: two separate open() calls

Each open() builds its own open file description. Two fds, two offsets, two sets of status flags, one shared inode.

Case B: dup(), dup2() or fork()

Duplication copies the pointer, not the object. Two fds, one open file description, therefore one shared offset. Seek on one and the other moves too.

/* fd-share.c : the shared-offset experiment */
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
    int a = open("/tmp/fd-demo.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
    write(a, "ABCDEFGHIJ", 10);

    /* --- Case B: duplicate the POINTER --- */
    int b = dup(a);                 /* new fd, SAME open file description */
    lseek(a, 0, SEEK_SET);          /* rewind through a ... */
    printf("B: offset seen via b = %ld\n", (long) lseek(b, 0, SEEK_CUR));
    /* prints 0 : b moved because it shares the offset with a */

    /* --- Case A: a brand new open() --- */
    int c = open("/tmp/fd-demo.txt", O_RDWR);  /* new description */
    lseek(a, 5, SEEK_SET);
    printf("A: offset seen via c = %ld\n", (long) lseek(c, 0, SEEK_CUR));
    /* prints 0 : c has its own independent offset */

    close(a); close(b); close(c);
    return 0;
}

Summary of who shares what:

Created by Shares the offset? Shares status flags (O_APPEND…)? Shares FD_CLOEXEC?
Second open() No No No
dup() / dup2() Yes Yes No (always cleared on the new fd)
fork() Yes Yes Yes (copied)
Threads in one process Yes (same table entirely) Yes Yes

This is also why a parent and child writing to the same redirected log file do not clobber each other: they inherited one open file description, so the offset advances for both. Two independent open() calls without O_APPEND would overwrite each other happily.

Step 3: shell redirection, implemented in four lines

Now the payoff. dup2(oldfd, newfd) means: close newfd if it is open, then make newfd point at the same open file description as oldfd. That is exactly what > does in your shell.

/* redirect.c : reimplementing "ls -l > /tmp/out.txt 2>&1" */
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>

int main(void)
{
    pid_t pid = fork();
    if (pid == 0) {
        /* --- child: rewire the fd table BEFORE exec --- */
        int fd = open("/tmp/out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if (fd == -1) { perror("open"); _exit(1); }

        dup2(fd, STDOUT_FILENO);   /* slot 1 now points to our file      */
        dup2(fd, STDERR_FILENO);   /* slot 2 too: this is the "2>&1" part */
        close(fd);                 /* slot 3 no longer needed; the file
                                      stays open because 1 and 2 still
                                      reference the same description     */

        char *argv[] = { "ls", "-l", NULL };
        execvp("ls", argv);        /* fd table survives exec */
        _exit(127);
    }
    wait(NULL);
    return 0;
}

Three things worth underlining:

  1. The fd table survives execvp() (unless a descriptor is marked close-on-exec). That is the only reason redirection works at all: the shell sets up the table, then replaces the program image.
  2. Order matters. cmd > file 2>&1 sends both streams to the file, while cmd 2>&1 > file points stderr at the old terminal and only stdout at the file, because 2>&1 copies whatever fd 1 happened to be at that moment.
  3. The old trick without dup2 is close(1); open("file", ...); which works because open() returns the lowest free descriptor, now 1. dup2() is safer because it is atomic.

A note on stdio buffering

If you mix printf() with dup2() in the same process, call fflush(stdout) before and after rewiring. FILE * streams are a userspace layer sitting on top of a descriptor; the buffered bytes are in your heap, not in the kernel, and they will be flushed to whatever fd 1 points to at flush time.

linux terminal code

Step 4: why closing one descriptor does not close the file

The open file description carries a reference count. Every fd table entry that points at it, in any process, counts as one reference. close() only removes the entry from your table and decrements that counter. The underlying file is released when the counter hits zero, and the inode itself is only freed when the link count on disk and the open count both reach zero. You will find the same thinking at another shop that gets it right.

Practical consequences you have probably met in production:

  • Deleted but still growing logs. rm app.log unlinks the directory entry, but a running daemon still holds a descriptor. df shows the disk as full while du shows nothing. The space returns only when the process closes the fd or restarts. lsof +L1 finds these.
  • Closing the duplicate is harmless. In the redirection example above, close(fd) did not close the file, because fds 1 and 2 still referenced the same description.
  • Half-closed sockets. After fork(), a TCP connection is not actually torn down until every copy of the descriptor is closed. A forgotten fd in a forked child keeps the connection alive, which is why servers leak sockets.
  • Temporary files that vanish on exit. Open a file, unlink it immediately, keep writing. The data is reachable only through your fd and disappears automatically when the process dies. This is what O_TMPFILE formalises.

Inspecting file descriptors on a live system

Everything above is observable at runtime. Linux exposes each process’s fd table as a directory of symbolic links:

# every descriptor of a process, with its target
ls -l /proc/<pid>/fd

# the same from inside your own shell
ls -l /proc/self/fd

# level 2 data: offset and status flags of a single description
cat /proc/<pid>/fdinfo/3

# who holds this file open?
lsof /var/log/app.log

# deleted files still held open (the "disk full" mystery)
lsof +L1

# current and maximum descriptors for the shell
ulimit -n          # soft limit
ulimit -Hn         # hard limit
cat /proc/sys/fs/file-max   # system-wide ceiling

/proc/<pid>/fdinfo/3 literally prints the pos: (offset) and flags: fields of the open file description. Open the same file twice from two shells and compare the two pos: values to prove the independence we demonstrated in C.

Descriptor limits and the errors they produce

Error Meaning Where to look
EMFILE This process hit its own fd limit ulimit -n, systemd LimitNOFILE=
ENFILE The whole system ran out of open file descriptions /proc/sys/fs/file-max
EBADF The integer does not index a valid slot (double close, use after close) Your code
linux terminal code

Modern habits worth adopting

  • Always pass O_CLOEXEC to open(), and use SOCK_CLOEXEC, accept4(), pipe2() and dup3(). Without it, every descriptor leaks into every child you exec, which is both a resource leak and a security hole.
  • Prefer openat() and openat2() when resolving paths relative to a directory fd. It avoids whole classes of symlink race conditions.
  • Check the return value of close() on data you care about, and never retry a failed close() on Linux: the descriptor is already gone and the number may have been reused by another thread.
  • Remember that descriptors are a process-wide, thread-shared resource. Two threads calling dup2() on the same target can race; that is precisely why dup3() exists.
  • Everything is an fd. epoll, signalfd, timerfd, eventfd, pidfd_open(), memfd and io_uring rings all hand you descriptors, so the same table, the same refcounting and the same inheritance rules apply.

Putting it all together

Understanding how file descriptors work in Linux really comes down to four sentences:

  1. A descriptor is an index into a per-process table, and the kernel always gives you the lowest free index.
  2. Each table entry points to an open file description, which owns the offset and the status flags.
  3. Duplicating a descriptor copies the pointer, so offsets are shared; opening the file again creates a new description, so offsets are independent.
  4. The file is released only when the reference count of the description drops to zero, which is why close() is cheap, safe and frequently not the end of the story.

Compile the three programs above, watch /proc/self/fdinfo while they run, and the abstraction stops being abstract.

FAQ

What is a file descriptor in an operating system?

It is a non-negative integer that identifies an open I/O resource within a process. In Linux it indexes the process’s file descriptor table, whose entries point to kernel structures describing the open file, pipe, socket or device. Windows uses the equivalent concept under the name handle, although handles are opaque values rather than small integers.

Why does open() usually return 3?

Because slots 0, 1 and 2 are already filled with stdin, stdout and stderr inherited from the shell, and the kernel always allocates the lowest unused descriptor. If you close stdin first, the next open() will return 0.

What is the difference between a file descriptor and a FILE pointer?

A file descriptor is a kernel-level integer used by system calls such as read() and write(). A FILE * is a userspace C library structure that wraps a descriptor and adds buffering and formatting. Convert between them with fileno(fp) and fdopen(fd, mode), and remember to fflush() before mixing the two.

Do two file descriptors always share the same offset?

No. They share an offset only when they point to the same open file description, which happens after dup(), dup2(), fcntl(F_DUPFD) or fork(). Two separate open() calls on the same path produce independent offsets. Understanding UNIX Pipes and File Descriptors tackles the same question from another angle.

Does closing one descriptor close the file?

Only if it was the last reference. close() clears your table slot and decrements the reference count of the open file description; the file is actually released when that count reaches zero across all processes.

What does ulimit -n 65535 do?

It raises the soft limit on the number of descriptors a process may hold to 65535, up to the hard limit. It is a common tuning step for servers handling many concurrent sockets, since every connection costs at least one descriptor. For services managed by systemd, set LimitNOFILE= in the unit file instead of relying on the login shell.

How do I see which files a running process has open?

List /proc/<pid>/fd for the symlink targets, read /proc/<pid>/fdinfo/<fd> for the offset and flags, or use lsof -p <pid>. For descriptors referring to already deleted files, lsof +L1 is the fastest diagnostic. wordpress.com published something useful on the subject.

Are sockets file descriptors?

Yes. socket() and accept() return ordinary descriptors from the same table. They have no meaningful file offset, so lseek() fails with ESPIPE, but inheritance, dup2() and reference counting behave exactly as described above.

Latest Posts

No Posts Found!

Banner of the Day

NewsLetter

Do not miss our news
Sign up and receive the latest news of our company
Newsletter

Contact Info
Copyright © 2022 I-4 Linux. All Rights Reserved.