CSE Roadmap

Core tier · about 3 hours · 8 parts

Part 4 of 8 · 3 min read

Open files

Think of a desk with three trays: one for papers to read, one for finished work and one for complaints. A process begins with three such trays, and the shell can swap what they lead to. The analogy stops in one place: trays hold paper, and descriptors are small numbers that the kernel maps to files or devices.

In plain words: Every process starts with three open standard streams, numbered by their descriptors (page 2): descriptor 0 is standard input (the keyboard by default), 1 is standard output (the screen), and 2 is standard error (where messages about problems go). A shell can redirect them to files or pipes.

The key lines.

The directory /proc/PID/fd shows each open descriptor as a link to the real file or device. A program can read its own with readlink:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>

static void show(int fd) {
    char path[64], target[PATH_MAX];
    snprintf(path, sizeof path, "/proc/self/fd/%d", fd);
    ssize_t n = readlink(path, target, sizeof target - 1);
    if (n < 0) { printf("fd %d: not open\n", fd); return; }
    target[n] = '\0';
    printf("fd %d -> %s\n", fd, target);
}

int main(void) {
    int fd = open("/etc/hostname", O_RDONLY);
    for (int i = 0; i <= fd; i++) show(i);
    close(fd);
    return 0;
}

Run as ./a.out < /dev/null > o.txt 2> /dev/null, which redirects all three streams, and then cat o.txt:

fd 0 -> /dev/null
fd 1 -> /tmp/ost/o.txt
fd 2 -> /dev/null
fd 3 -> /etc/hostname

The shell changed what descriptors 0, 1 and 2 point to before the program began. The program itself opened the file /etc/hostname, and the kernel gave it the next free number, 3. The rule is that open always returns the smallest unused descriptor. That is the reason the copy program on page 2 got 3 for the input and 4 for the output.

Descriptors are also a limited resource. A process that opens files and never closes them eventually runs out of slots, and open then fails with the error code for "too many open files". The command ls /proc/PID/fd | wc -l counts how many a process holds.

Standard streams

The standard streams are the three file descriptors that a process normally has open when it starts: standard input (0), from which it reads its input, standard output (1), to which it writes its normal results, and standard error (2), to which it writes error messages. The shell can attach each of them to a terminal, a file or a pipe.

Example: printf writes to descriptor 1, so redirecting descriptor 1 to a file sends the text to that file.

Check yourself: 1. Which number does the next open return when 0, 1, 2 and 3 are in use? 2. What does descriptor 2 carry? 3. How can you count the files a process has open?