Linux commands
Browse topics

Finding open files and ports with lsof

Version
unversioned
Review
Draft

Summary#

lsof lists open files and the processes that hold them. Network sockets count as files, so it also shows which process listens on a port.

Syntax#

sh
lsof /var/log/app.log
lsof -p "$pid"
lsof -nP -iTCP:8080 -sTCP:LISTEN
lsof -t -iTCP:8080 -sTCP:LISTEN
lsof +L1

A file name selects the processes that have that file open. -i selects network files, -n and -P keep addresses and ports numeric, and -t prints only process IDs. +L1 lists open files with no remaining directory entry, which are deleted files that still occupy space. Add -a to require all selections instead of any of them.

Example#

sh
(
  set -eu
  dir=$(mktemp -d)
  holder=
  trap 'if [ -n "$holder" ]; then
      kill "$holder" 2>/dev/null || true
      wait "$holder" 2>/dev/null || true
    fi
    rm -rf -- "$dir"' EXIT

  sleep 30 > "$dir/held.log" &
  holder=$!
  test "$(lsof -t "$dir/held.log")" = "$holder"
  echo 'lsof found the process holding the file'

  rm "$dir/held.log"
  lsof -a -p "$holder" +L1 -Fn | sed -n 's/^n.*held\.log (deleted)$/the deleted file is still open/p'
)

Expected output#

Text
lsof found the process holding the file
the deleted file is still open

Common mistakes#

Without root, lsof usually cannot inspect processes that belong to other users, so empty output does not prove that a port or file is unused. Run it with sudo when you need every process. Selections are combined with OR: lsof -p "$pid" -i lists the process's files and also every network file, so add -a to intersect them. lsof exits with status 1 when it finds nothing, which stops a set -e script. Deleting a large file does not free its space while a process still holds it; restart or signal that process after checking lsof +L1.

Version applicability#

This entry describes lsof 4.99, which is not installed by default on every distribution. Output columns and some options differ between operating systems.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0