lsof lists open files, and on Unix nearly everything is a file: regular files, directories, network sockets, pipes, and devices.
Find deleted files still held open (classic disk-space mystery)¶
lsof | grep deleted
sudo lsof +L1 # files with link count 0 but still open (a more targeted way to find the same thing)
df shows a full disk, but no large files are visible with du. This is the usual cause: a process (often a log writer) still has a file descriptor open on a file that was deleted, so the space is not released until the process exits or is told to reopen its logs (systemctl restart <service>, or kill -HUP <pid> for daemons that support it).
What has a path open¶
lsof /var/log/app.log # who has this specific file open
lsof +D /var/log # everything open under a directory
lsof -u alice # files opened by a user
lsof -c nginx # files opened by processes whose command starts with "nginx"
lsof -p 1234 # files opened by one PID
Network sockets¶
sudo lsof -i :443 # what is using port 443
sudo lsof -i tcp -sTCP:LISTEN # all listening TCP sockets
ss (see ss) is faster for socket-only queries; lsof -i is handy when you also want the process's other open files in the same view.
Counting and summarising¶
lsof | awk '{print $1}' | sort | uniq -c | sort -rn | head # which commands hold the most open files
If a process is hitting the open-files limit (Too many open files), check ulimit -n for that process and /proc/<pid>/limits, and count with lsof -p <pid> | wc -l.