lsof -p: List Files a Process Has Open
lsof -p <pid> shows every open file descriptor a process holds: regular files, sockets, pipes, and devices.
A long-running test process that leaks file descriptors eventually hits its ulimit and fails with EMFILE. lsof -p lets you count and categorize what it is holding.
What it does
lsof -p <pid> lists the open files for one process. The FD column shows the descriptor number (or cwd, txt, mem), and TYPE shows REG, IPv4, sock, FIFO, and so on. Counting the lines tells you how close a process is to its descriptor limit.
Common usage
lsof -p 4242
lsof -p 4242 | wc -l # how many fds it holds
lsof -p 4242 | grep -c sock # just sockets
# count fds the fast way, no lsof needed
ls /proc/4242/fd | wc -lOptions
| Flag | What it does |
|---|---|
| -p <pid> | Restrict to one process |
| -a | AND the selection filters together |
| -d <fd> | Restrict to specific descriptors (e.g. -d 0-2) |
| +L1 | Show unlinked (deleted but still open) files |
| -n -P | Skip host and port name resolution |
In CI
When a job fails with "EMFILE: too many open files" or "Too many open files", run lsof -p <pid> | wc -l and compare it to ulimit -n. A steadily climbing count across the run points at a leak (unclosed sockets or watchers). lsof +L1 finds deleted-but-open log files that still consume disk.
Common errors in CI
"lsof: no process found" means the PID already exited. Permission gaps (no output for another user’s process) need sudo. On minimal images without lsof, ls /proc/<pid>/fd | wc -l gives the same descriptor count with no extra package.