Log inStart free
LESSON 1.13 · 6 STAGES · 2 CONTROLS · 3 CHECKSPRO · PREVIEW

Pipes and file descriptors

Watch a shell connect two programs with a pipe and a few small numbers.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 2 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 1.13 · PIPE BAY1 PROCESS · FDS 0, 1, 2 → TERMINAL
01
Stage 1 of 6 · FD table
Each process has a file-descriptor table. Its fds 0, 1 and 2 point to the terminal.
Explain it simply

This box is the shell, the program that runs your command. Its table maps small numbers, called file descriptors or fds, to open files. Every program reads fd 0, writes fd 1 and sends errors to fd 2. Here all three lead to the terminal, as the lsof tool would list them.

The shell, pid 6735, has fds 0, 1 and 2. All three point to the terminal /dev/pts/0.

process and its fd tablefd and referenceopen file and bytesoutput and resultstderr and waiting
terminal · /dev/pts/03 fds$ python3 train.py | grep loss > losses.txtshellpid 6735running0uCHR/dev/pts/01uCHR/dev/pts/02uCHR/dev/pts/0what lsof -p 6735 -d 0-9 listsCOMMANDPIDFDTYPENAMEshell67350uCHR/dev/pts/0shell67351uCHR/dev/pts/0shell67352uCHR/dev/pts/0terminal · /dev/pts/03 fds$ python3 train.py | grep loss > losses.txtshellpid 6735running0uCHR/dev/pts/01uCHR/dev/pts/02uCHR/dev/pts/0what lsof -p 6735 -d 0-9 listsCOMMANDPIDFDTYPENAMEshell67350uCHR/dev/pts/0shell67351uCHR/dev/pts/0shell67352uCHR/dev/pts/0
Toy: 3 processes · one CPU · a 32-byte pipe (Linux: 64 KiB) · pids and inodes are stand-ins
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
table[fd]→open file\mathrm{table}[\sy{fd}{param}{\mathit{fd}}] \rightarrow \sy{file}{data}{\text{open file}}
table[0], table[1], table[2]→/dev/pts/0\mathrm{table}[0],\ \mathrm{table}[1],\ \mathrm{table}[2] \rightarrow \texttt{/dev/pts/0}

An fd is an index into the table of one process.

Common mix-ups

MYTHThe first command finishes before the second one starts.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01With 2>&1, how many lines end up in losses.txt?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 2 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.