Why use it
When you need answers to questions like:
- "Which process holds this port?"
- "What has this file locked?"
- "Why is the disk full when
dushows little usage?"
lsof is the tool to reach for. Without sudo it shows only your own processes;
with sudo it shows all of them.
Most common forms
lsof -p 1234 # all fds of a specific [[process-and-pid]]
lsof -i # all network sockets
lsof -i :8080 # who is listening on or connected to port 8080
lsof -i tcp # TCP only
lsof -nP -i # no resolution: -n skips host lookup, -P skips port lookup
lsof /var/log/app.log # who has this specific file open
lsof +D /var/lib/docker # all open files inside a directory (-D = recurse)
Most useful one-liner: lsof | grep deleted
When df -h shows the disk full but du -sh / does not:
sudo lsof | grep deleted
These are processes that hold open a file already removed from the filesystem. The inode stays alive until the file descriptor is closed. The most common culprit is an application with log rotation that never reopened its log file.
Output columns
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 900 www 6u IPv4 12345 0t0 TCP *:80 (LISTEN)
- FD: number plus access mode.
6uis fd 6, open for read+write.cwd,rtd,txt, andmemare special types (cwd = current directory, txt = binary, mem = mmap). - TYPE:
REG(regular file),DIR,CHR(char device),IPv4/IPv6,unix,FIFO. - NAME: path, or
host:port -> host:portfor sockets.
Alternative via /proc
Without lsof you can see the same information through /proc/<pid>/fd/*:
ls -l /proc/900/fd/ # each fd is a symlink to its target
lsof is a convenient aggregator of exactly that data.