lsof: List Open Files

lsof for open files, network connections, process file descriptors, and recovering deleted files.

Overview

Overview lsof (List Open Files) is uniquely powerful on Linux because "everything is a file" — regular files, directories, sockets, pipes, devices, and more all appear in lsof output. It's an essential tool for diagnosing resource leaks, connection issues, and deleted-file problems.

Basic usage and filtering: - lsof (no args): lists ALL open files for ALL processes — massive output, always filter - lsof -i :80: files related to port 80 (TCP and UDP listeners and connections) - lsof -i TCP:22: specifically TCP port 22 - lsof -i 4: IPv4 only, lsof -i 6: IPv6 only - lsof -p PID: all files opened by a specific process - lsof +D /var/log: all files open in a directory tree (+ means recursive) - lsof /path/to/file: which processes have a specific file open - lsof -u username: files opened by a user - lsof -c nginx: files opened by processes with name matching "nginx"

FD column meanings: cwd (current working directory), txt (program executable), mem (memory-mapped file), DEL (deleted but still open), 0 (stdin), 1 (stdout), 2 (stderr), numbers (regular file descriptors). Suffix u=read+write, r=read, w=write.

TYPE column: REG (regular file), DIR (directory), CHR (character device), BLK (block device), FIFO (named pipe), IPv4/IPv6 (network socket), unix (Unix domain socket), PIPE (anonymous pipe).

Recovering deleted files: When a process has a file open that has been deleted (unlinked), the file's inode and data remain on disk until all references are closed. The FD column shows "DEL" and the TYPE is REG. Access via /proc/PID/fd/N: cat /proc/$(pgrep myapp)/fd/5 > /tmp/recovered_file.

Performance: lsof with no filters is slow (iterates /proc for every process). Always filter: lsof -n (no DNS) -P (no port names) for speed.

Key concepts

  • lsof -i for network
  • -p for process
  • FD column meaning
  • /proc/PID/fd recovery

Interview questions

  • A process deleted a large log file but disk space didn't free up. How do you find and recover it?
  • How would you find which process is listening on port 8080 without using netstat or ss?

Sign up free to read the full topic

More Linux topics

Start free on Cariara · Coding problems · System design studio