The questions you are answering
When a process is slow, stuck or dead, work from cheap and broad to expensive and narrow:
- Is it using CPU, and in user or kernel mode?
top,htop - What is its state?
/proc - What is it asking the kernel for?
strace - Where is the CPU time going in the code?
perf - What files and sockets does it hold?
lsof,ss - Is it hitting a limit?
ulimit,/proc/<pid>/limits - Why did it crash? core dump and
gdb
All commands below are Linux. macOS equivalents are noted where they differ.
top and htop
The header line load average: 3.10, 2.50, 1.80 is the 1-, 5- and 15-minute average of runnable tasks plus tasks in uninterruptible sleep (D), so on Linux a high load with idle CPUs often means processes stuck on disk or NFS. Compare it with the number of CPUs.
The CPU line splits time into us (user), sy (kernel), ni (niced), id (idle), wa (waiting for I/O), hi/si (hardware and software interrupts) and st (stolen by the hypervisor). A process pinned at 100% sy is making system calls or faulting heavily; high st on a VM means a noisy neighbour.
Per process: VIRT (reserved address space, often huge and meaningless), RES (resident in RAM), SHR (shared, such as libraries), S (state: R, S, D, Z). Useful keys: H toggles per-thread view, 1 shows each CPU, P/M sort by CPU or memory. top -H -p <pid> shows one process's threads, which is how you spot the one thread at 100%. htop adds colour, a tree view and easier sorting. (macOS ships a different top with other flags; htop works on both.)
/proc
Every process has a directory /proc/<pid> of virtual files generated on read:
| Path | What it tells you |
|---|---|
status | State, VmRSS, Threads, voluntary and involuntary context switches |
maps, smaps | Every memory mapping, with per-mapping RSS and huge-page use in smaps |
fd/ | One symbolic link per open descriptor |
limits | The soft and hard resource limits in effect |
task/<tid>/ | The same information per thread |
cmdline, environ, cwd, exe | How it was started and from where |
System-wide: /proc/cpuinfo, /proc/meminfo, /proc/interrupts (per-CPU interrupt counts, handy for checking IRQ steering) and /proc/sys/ (kernel tunables, also reachable with sysctl). macOS has no /proc; use ps, vmmap, lsof and sysctl.
strace: the system-call view
strace -f -tt -T ./app # follow threads/children, timestamps, time in each call
strace -p 12345 -e trace=network # attach to a running pid, only socket calls
strace -c -f -p 12345 # count calls and time per call type; Ctrl-C for the summary
strace answers "what is it waiting for?": a process hung in futex(...) is waiting on a lock or condition variable, one stuck in read(5, ...) is waiting on descriptor 5 (look it up in /proc/<pid>/fd/5), and an ENOENT on open reveals the missing config file. It uses ptrace and stops the process on every call, which can slow it by a large factor, so do not attach it casually to a latency-critical production process. (macOS: dtruss, which needs System Integrity Protection relaxed.)
perf: where the cycles go
perf stat -e cycles,instructions,cache-misses,context-switches ./app # counters
perf record -g ./app # sample call stacks into perf.data
perf report # browse the hottest functions and their callers
perf top # live view of the hottest functions system-wide
perf reads the CPU's hardware performance counters and samples stacks with low overhead. In perf stat output, instructions per cycle (IPC) is the first number to read: below 1 on a modern core usually means stalls on memory or branch mispredictions; 2 to 4 means the core is busy computing. perf record -g needs frame pointers or DWARF information (--call-graph dwarf) to give clean stacks for optimised code, and unprivileged use depends on kernel.perf_event_paranoid. (macOS: Instruments, or sample <pid>.)
lsof, ss and netstat
lsof -p 12345 # every file, socket and pipe the process holds
lsof -i :8080 # who has port 8080 open
ss -tlnp # listening TCP sockets, numeric, with owning process
ss -tanp # all TCP sockets and their states
ss -s # summary counts per state
In ss output, a growing Recv-Q on an established socket means the application is not reading fast enough; a growing Send-Q means the peer or network is not keeping up. Thousands of TIME-WAIT or CLOSE-WAIT sockets point to connection churn or a program that never closes its sockets. netstat (from the older net-tools package) shows similar information; macOS has netstat and lsof but not ss.
ulimit
ulimit -a # all limits for this shell
ulimit -n # max open file descriptors (often 1024 by default)
ulimit -n 65536 # raise the soft limit, up to the hard limit
ulimit -c unlimited # allow core dumps of any size
Limits are per process and inherited by children, with a soft value (enforced) and a hard ceiling (only root can raise it). Persistent settings live in /etc/security/limits.conf for login sessions, or LimitNOFILE= in a systemd unit for services, which do not read limits.conf.
Worked example
Too many open files
A market-data gateway runs fine for hours, then every new connection fails with EMFILE: Too many open files. Walk through the diagnosis out loud.
Show solutionHide solution
EMFILE means this process hit its descriptor limit (ENFILE would be the system-wide table). Steps:
pid=$(pidof gateway)
grep 'open files' /proc/$pid/limits # e.g. soft 1024, hard 4096
ls /proc/$pid/fd | wc -l # e.g. 1024: at the limit
lsof -p $pid | awk '{print $5}' | sort | uniq -c | sort -rn # descriptor types
ss -tanp | grep gateway | awk '{print $1}' | sort | uniq -c # TCP states
Interpret the result. If the count grows steadily with time and most descriptors are sockets in CLOSE-WAIT, the peers have closed their end but the program never calls close: a descriptor leak, so fix the code path that drops connections. If the count is flat near the limit and matches real concurrent connections, the limit is simply too low: raise it with LimitNOFILE= in the service unit (and check the hard limit), then confirm in /proc/<pid>/limits after restart. Raising the limit to hide a leak only delays the failure.
Core dumps and gdb
When a process dies from SIGSEGV, SIGABRT and similar signals, the kernel can write its memory and registers to a core file. Three things decide whether you get one:
- the core-size limit:
ulimit -c unlimitedin the shell that starts the program; /proc/sys/kernel/core_pattern: a file-name template, or a pipe to a handler. On systemd distributions it pipes tosystemd-coredump, and you list and open dumps withcoredumpctl listandcoredumpctl gdb <pid>;- whether the binary has debug information: build with
-g(even at-O2) so the debugger can map addresses to source lines and variables.
A shell reports a crash by exit status 128 plus the signal number: 139 is , SIGSEGV; 134 is , SIGABRT (typically from abort or a failed assert).
The basic gdb session:
gdb ./app core # or: coredumpctl gdb <pid>
(gdb) bt # backtrace of the crashing thread
(gdb) frame 1 # select a frame from the backtrace
(gdb) info locals # local variables in that frame
(gdb) print *o # inspect an expression
(gdb) list # source around the current line
(gdb) info threads # all threads; "thread apply all bt" for every stack
On macOS use lldb (bt, frame select 1, frame variable); cores go to /cores when enabled.
Worked example
reading a crash
This program, built with c++ -std=c++20 -g -O0 crash.cpp -o crash, prints one line and then the shell reports exit status 139. Explain what the backtrace will show and what to conclude.
#include <cstdio>
#include <vector>
struct Order { int id; double px; };
double notional(const Order* o, int qty) {
return o->px * qty; // crashes when o is null
}
int main() {
std::vector<Order*> book = {new Order{1, 101.5}, nullptr};
for (int i = 0; i < 2; ++i)
std::printf("order %d notional %.1f\n", i, notional(book[i], 100));
}
Show solutionHide solution
The first line printed is order 0 notional 10150.0 (). Exit status 139 is : SIGSEGV.
Loading the core, bt shows frame #0 in notional (o=0x0, qty=100) at crash.cpp:7 and frame #1 in main at the printf line; in frame 1, info locals shows i = 1. Running the same binary under lldb on macOS reports the fault as a bad access at address 0x8, which is the clue to read: the program dereferenced a null pointer plus 8, and 8 is the offset of px inside Order (an int padded to 8 bytes for the double). A fault address that is a small number is almost always a field access through a null pointer; a fault address that looks like a real heap address points instead to a use-after-free or corrupted pointer.
Two practical notes. When stdout is a pipe or file it is fully buffered, so on a crash lines already "printed" can vanish from the log; do not trust the last log line to locate a crash, and flush or log to stderr for crash-relevant messages. And keep debug symbols for release builds (-g, stripped into a separate file if needed) so production cores are readable.
Knowledge check
A Linux box shows load average 12 on 8 CPUs, but top shows the CPUs about 70% idle. What is the most likely explanation?
Knowledge check
A service is stuck and uses no CPU. Which command most directly tells you what it is blocked on?
Knowledge check
perf stat on a hot loop reports 0.4 instructions per cycle and a high cache-miss count. What does that suggest?
Key takeaways
- Triage in order:
top/htop(CPU, user versus kernel, threads),/proc(state and limits),strace(what it asks the kernel),perf(where cycles go),lsof/ss(descriptors and sockets). - Linux load average includes D-state tasks; high load with idle CPUs means I/O waits.
straceis invasive;perfis cheap. Read IPC first inperf stat.- Check limits in
/proc/<pid>/limits; services take limits from their systemd unit, not limits.conf. - Enable cores (
ulimit -c,core_pattern,coredumpctl), build with-g, thenbt,frame,info locals. Exit status 139 isSIGSEGV; a small fault address is a null-pointer field access.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).