CSE Roadmap

Core tier · about 3 hours · 8 parts

Part 6 of 8 · 2 min read

strace and manuals

Think of a security camera over a doorway that records each time a person passes. The tool strace is such a camera at the door of the kernel. The analogy stops in one place: a camera is passive, and strace slows the program because it stops it at every call.

In plain words: The tool strace prints every system call a program makes, with its arguments and result. It is the most direct way to confirm what page 2 described. Useful forms:

Command What it shows
strace ./prog Every system call, in order
strace -c ./prog A summary table: calls, errors and time per system call
strace -e trace=read,write ./prog Only the named calls
strace -f ./prog Also follow child processes (Level 1)

For the earlier cpu program, strace -c produced a table like this one:

% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 29.81    0.000031          10         3           fstat
 22.12    0.000023          11         2           write
  ...

Even a "Hello world" shows more calls than the one write: the program loader maps memory, opens libraries and sets up the process before main runs. Counting only the calls inside your own code would miss these.

The manual pages tell you what a call does. The manual is split into numbered sections. Section 2 covers system calls and section 3 covers library functions, so man 2 write shows the system call and man 3 printf the library function. When two sections hold the same name, the number picks the right one. A page lists the arguments, the return value and the errors (the errno values from page 2) that the call may set.

A debugging recipe that uses everything on this page:

  1. A program fails with an error. Run strace ./prog 2>&1 | tail to see its last system calls, and look for a result of -1 with an error name.
  2. The error name, such as ENOENT, is explained in man 2 open.
  3. A program seems stuck. Find its PID with ps, read /proc/PID/status for the state, and look at /proc/PID/fd to see which files it holds.
  4. A program is slow. Run it under time to see whether the time is user or system, and under strace -c to see which call dominates.

Read it as

Programs are black boxes only until you watch them cross into the kernel. Every effect they have on the world passes through a system call.

Check yourself: 1. Which manual section describes system calls? 2. What does strace -c print? 3. Which file shows whether a process is running or sleeping?