Skip to content
Visual explainer 4h to learn 5 steps

File descriptors: open, read, write, close

Copy files with raw system calls, handling short reads and writes.

By Invicly Tech, , in Linux System Programming. About 13 minutes to read.

Topic 8 of 42

In short

A file descriptor is a small integer that refers to an open file, pipe, socket or device in the kernel. open returns one, read and write move bytes through it, and close releases it. Because the same calls work for every kind of descriptor, this is the core of the everything-is-a-file design.

Explained simply

When a program wants to use a file, it asks the kernel to open it. The kernel does the hard work and hands back a small number, such as 3. That number is a file descriptor. It works like a ticket at a coat check: you keep the ticket, the kernel keeps the coat, and you show the ticket every time you want something.

Every program starts with three descriptors already open. 0 is standard input, 1 is standard output and 2 is standard error. The shell sets them up before your program runs. That is why ./prog > out.txt works: the shell points descriptor 1 at the file, and your program never knows.

read and write move bytes through a descriptor. They promise at most the amount you ask for, not exactly that amount. A read from the keyboard returns one line. A read from a pipe returns what has arrived so far. Correct code always loops until it has everything.

When you are done, close the descriptor. Each process may only have a limited number open at once, often 1024. A long-running server that forgets to close files will one day fail with "Too many open files".

Press Play on a diagram to walk through it one step at a time.

LayersFrom descriptor to data
  1. 1
    fd number (per process)

    Index into the process descriptor table, such as 3.

  2. 2
    Open file description

    Kernel object holding the offset, flags and access mode.

  3. 3
    Inode (via the VFS)

    File metadata and where its data blocks live.

  4. 4
    File system and block device

    Where the bytes are actually stored.

SequenceThe system calls behind cat in.txt > out.txt
cat
Kernel
  1. 1openat("in.txt", O_RDONLY)
    cat to Kernel: openat("in.txt", O_RDONLY)
  2. 2returns fd 3
    Kernel to cat: returns fd 3
  3. 3read(3, buf, 131072)
    cat to Kernel: read(3, buf, 131072)
  4. 4returns 5000, then 0 on the next call (EOF)
    Kernel to cat: returns 5000, then 0 on the next call (EOF)
  5. 5write(1, buf, 5000): fd 1 is out.txt
    cat to Kernel: write(1, buf, 5000): fd 1 is out.txt
  6. 6close(3), then exit
    cat to Kernel: close(3), then exit

In depth

open flags and the mode argument

The flags argument mixes three kinds of options. First, exactly one access mode: O_RDONLY, O_WRONLY or O_RDWR. Second, creation flags that only matter while opening: O_CREAT creates a missing file, O_EXCL makes O_CREAT fail if the file exists, O_TRUNC empties an existing file, and O_CLOEXEC closes the descriptor automatically on exec. Third, status flags that stay with the open file, such as O_APPEND and O_NONBLOCK.

The third argument, the mode, is only used when a file is actually created. The umask then removes bits from it, so 0644 is a common choice. If you pass O_CREAT and forget the mode, open reads whatever happens to be in that argument slot and the file gets random permissions.

On modern Linux, glibc's open is implemented with the openat system call, so strace shows openat(AT_FDCWD, ...) even though you wrote open.

  • Write-and-replace: O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644
  • Create only if new: O_WRONLY | O_CREAT | O_EXCL, 0600
  • Read only: O_RDONLY | O_CLOEXEC (no mode needed)
MapThe three groups of open flags
open(path, flags, mode)
  • Access mode (pick one)
    • O_RDONLY
    • O_WRONLY
    • O_RDWR
  • Creation flags (used once)
    • O_CREAT
    • O_EXCL
    • O_TRUNC
    • O_CLOEXEC
  • Status flags (stay with the file)
    • O_APPEND
    • O_NONBLOCK
    • O_SYNC
  • mode (only with O_CREAT)
    • Such as 0644 or 0600
    • The umask removes bits

Who shares what: two opens versus one dup

Each successful open creates a new open file description in the kernel. It holds the current offset and the status flags. The descriptor number in your process is just a pointer to it.

If you open the same file twice, you get two descriptions with two independent offsets. Writing through both can overwrite the same bytes. If you dup a descriptor, or fork a child, the copies point to the same description. They share one offset, so writes follow each other instead of colliding. This is why a parent and child that both write to an inherited log file do not overwrite each other.

Closing one copy does not close the others. The description is freed only when the last descriptor that refers to it is closed.

Compareopen() twice vs dup() or fork()
open() the same file twice
  • Two open file descriptions
  • Each has its own offset
  • Writes can overwrite each other
  • Flags such as O_APPEND set separately
dup() or fork()
  • One shared open file description
  • One shared offset
  • Writes follow one another
  • Closing one copy leaves the others open

Short reads, short writes and end of file

A short read is normal. A regular file near its end returns only what is left. A terminal in normal mode returns one line when you press Enter. A pipe or socket returns whatever bytes are already there. Only a return value of 0 means end of file.

write to a pipe or socket can also be short when the buffer on the other side is full, and a write to a regular file can be short when the disk fills up or a file size limit is reached. If a signal handler runs in the middle of a slow read or write, the call returns the bytes moved so far, or -1 with errno set to EINTR if nothing was moved yet.

So every robust program has two small loops: read until you have what you need or reach EOF, and write until every byte is out.

  • n > 0: got n bytes, maybe fewer than asked
  • n == 0: end of file (or the other side closed)
  • n == -1 and errno == EINTR: just try again
  • n == -1 otherwise: a real error, report it

Closing descriptors and the open file limit

close can fail too. On network file systems such as NFS, a write error may only be reported at close, so check its return value when you wrote data that matters. On Linux, do not retry close after EINTR: the descriptor is already released, and a retry could close a new file that another thread just opened with the same number.

Each process has a limit on open descriptors, RLIMIT_NOFILE. ulimit -n shows the soft limit, which is often 1024; ulimit -Hn shows the hard limit you may raise it to. systemd services can set LimitNOFILE=. Reaching the per-process limit gives EMFILE; the rarer system-wide limit gives ENFILE.

To look for leaks, list /proc/PID/fd: each entry is a symlink to the file, pipe or socket behind that number.

stdin, stdout and stderr are just numbers

unistd.h names the three standard descriptors STDIN_FILENO (0), STDOUT_FILENO (1) and STDERR_FILENO (2). Nothing in the kernel is special about them. They are simply the first three slots, filled in by whoever started your program.

Your program cannot assume they are a terminal. They might be a file, a pipe or /dev/null. isatty(STDOUT_FILENO) tells you if output goes to a terminal, which is how ls decides whether to print colours and columns.

One trap: if a program starts with descriptor 1 closed, the next open returns 1, because open always picks the lowest free number. Every later printf then writes into that file. Careful daemons therefore make sure 0, 1 and 2 are open, pointing them at /dev/null if needed, before opening anything else.

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Open files with flags and modes~50m
  2. 2
    Read and write in a loop~50m
  3. 3
    Handle short reads and writes~50m
  4. 4
    Close descriptors and avoid leaks~50m
  5. 5
    Use stdin, stdout and stderr descriptors~50m

Key points

  • 0, 1 and 2 are stdin, stdout and stderr; open returns the lowest free number.
  • read returns 0 at end of file and may return fewer bytes than requested.
  • write may also be partial on pipes and sockets, so loop until everything is written.
  • Unclosed descriptors leak and eventually hit the RLIMIT_NOFILE limit.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv) {
  if (argc != 3) return 2;
  int in = open(argv[1], O_RDONLY);
  int out = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
  if (in < 0 || out < 0) return 1;
  char buf[4096];
  ssize_t n;
  while ((n = read(in, buf, sizeof buf)) > 0)
    for (ssize_t off = 0; off < n; ) { ssize_t w = write(out, buf + off, n - off); if (w < 0) return 1; off += w; }
  close(in); close(out);
  return n < 0;
}

A minimal cp that handles short writes.

Watch short reads happen

This program reads standard input with a large 64 KiB buffer and reports every read call. Step 1: run it and type a few lines; each read returns one line, including the newline, because the terminal hands over input line by line. Press Ctrl-D to send end of file. Step 2: run ./a.out < /etc/services; now reads return full 65536-byte chunks and a smaller last one. Step 3: run cat /etc/services | ./a.out; chunk sizes now depend on how much cat had written into the pipe at that moment. Same code, three different patterns, and only the loop makes it correct in all of them.

c
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
  char buf[65536];
  ssize_t n;
  long calls = 0, total = 0;
  while ((n = read(STDIN_FILENO, buf, sizeof buf)) != 0) {
    if (n < 0) { if (errno == EINTR) continue; perror("read"); return 1; }
    calls++; total += n;
    fprintf(stderr, "read returned %zd\n", n);
  }
  printf("%ld calls, %ld bytes\n", calls, total);
  return 0;
}

Find a descriptor leak in a running process

A service starts failing with "Too many open files" after running for a day. Step 1: find its PID and count its open descriptors. Step 2: run the count again a few minutes later; if it keeps growing, something is not being closed. Step 3: group the targets to see what leaks: thousands of the same log file or socket type point straight at the bug. Step 4: compare with the limit the process really has, which may differ from your shell's ulimit.

bash
PID=$(pgrep -o myservice)
ls /proc/$PID/fd | wc -l                 # how many are open now
grep 'open files' /proc/$PID/limits      # soft and hard limit for this process
ls -l /proc/$PID/fd | awk '{print $NF}' | sed 's/[0-9]*]$//' | sort | uniq -c | sort -rn | head
# e.g. 1012 socket:[   -> a socket is opened per request and never closed
ulimit -n; ulimit -Hn                    # your shell's soft and hard limits

Quick reference

  • Create or overwrite: open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644)
  • Use exactly one of O_RDONLY, O_WRONLY, O_RDWR; with O_CREAT always pass a mode
  • read returns >0 bytes, 0 at end of file, or -1 with errno (retry on EINTR)
  • STDIN_FILENO is 0, STDOUT_FILENO is 1, STDERR_FILENO is 2
  • ls -l /proc/PID/fd shows every open descriptor and what it points to
  • EMFILE: this process hit its open file limit; check ulimit -n
  • On Linux, never retry close() after EINTR; the descriptor is already gone
  • strace -e trace=openat,read,write,close ./prog shows every descriptor call

Common mistakes

  • Assuming one read returns the whole file.
  • Forgetting the mode argument when using O_CREAT.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You call open(path, O_WRONLY | O_CREAT) with no third argument and no compiler checks. What permissions does a new file get?

Question 2

2A program calls close(1) and then opens a log file. Which descriptor number does open return?

Question 3

3A parent opens a file, forks, and both processes write to the inherited descriptor. What happens to the file offset?

Question 4

4You read from a terminal with a 4096-byte buffer. The user types hi and presses Enter. What does read return?

Question 5

5open fails with errno EMFILE. What does it mean?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a program that prints "hello" to stdout and "oops" to stderr using only write(). Run it as ./a.out > out.txt and explain which text stays on the screen.

  2. Exercise 2medium

    Write mycat: copy each file named on the command line to stdout, or copy stdin if no names are given. If one file fails, print the error and continue with the next.

  3. Exercise 3hard

    Prove that two open() calls give independent offsets while dup() shares one. Open the same file (at least 10 bytes) twice, dup the first descriptor, read 5 bytes through each of the three, and print each offset.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why does my first open() return 3?
Descriptors 0, 1 and 2 are already taken by stdin, stdout and stderr, and open always returns the lowest free number.
Can two processes use the same descriptor number for different files?
Yes. Descriptor numbers are private to each process, so fd 3 in one program has nothing to do with fd 3 in another.
How do I raise the number of files a process can open?
Run ulimit -n with a higher value (up to the hard limit) before starting the program, or call setrlimit(RLIMIT_NOFILE) in code. For a systemd service, set LimitNOFILE= in the unit file.
Do I need to close files before my program exits?
The kernel closes every descriptor when a process exits. Still close them yourself in long-running programs to avoid leaks, and check close() after writing important data, since some errors are only reported there.

Go deeper

ShareXLinkedInWhatsApp