Skip to content

lsof: find what has a file or port open

A practitioner guide to lsof: decode the FD column, find open files linux tools hide, hunt down what holds a port, and reclaim disk from deleted-but-open files with +L1.

lsof answers one question: which processes have which files open. On Linux that question is broader than it sounds, because almost everything is a file — a regular file on disk, a directory, a shared library mapped into memory, a pipe, a device node, and a TCP or UDP socket all land in the same table. That is why one command tells you what is listening on port 443, which process is pinning the filesystem you are trying to unmount, and why df insists the disk is full while du can only account for half of it. The trick to reading lsof is knowing that every row is one file descriptor held by one process — not one file. A file with three readers is three rows.

What you’ll accomplish

  • Read an lsof table column by column and decode the FD codes (cwd, txt, mem, 3u) that trip up everyone the first time.
  • Find which process is listening on a port and which peers are connected to it.
  • List everything a process, a user, or a directory subtree has open.
  • Find deleted-but-still-open files and reclaim the disk they are silently holding.
  • Know when to put lsof down and reach for ss or strace instead.

Prerequisites

  • lsof installed. lsof -v prints the version and build details. Install it with apt install lsof, dnf install lsof, or apk add lsof. Plenty of minimal container and cloud base images ship without it.
  • Root, or an honest understanding of what you cannot see. lsof works by reading /proc/<pid>/fd, and the kernel only lets you read descriptors belonging to your own processes. As an unprivileged user you get your own processes and nothing else — no error, no warning, just a shorter table. Almost every command below uses sudo for that reason.
  • A real /proc. lsof on Linux is fundamentally a /proc reader. Inside a container with a masked or restricted /proc, it sees only that container’s processes, which is usually what you want but occasionally not what you expect.
  • A note on scope: if your question is purely about sockets — what is listening, what is connected, what state is it in — ss is the better tool on any modern system. It reads netlink instead of walking every process, so it is faster and does not need root to enumerate listeners. Reach for lsof when you need to tie a socket back to a process and see that process’s other open files in the same view, or when the question involves files at all.

How it works

Three separate things get conflated when people say “open file,” and lsof’s output only makes sense once you separate them.

A process owns a file descriptor table — a small array of integers, one per open thing, exposed at /proc/<pid>/fd. Descriptor 3 in one process has nothing to do with descriptor 3 in another. Each descriptor points at an open file description in the kernel, which holds the mode (read, write, read/write) and the current byte offset. That description in turn points at an inode, which is the actual object: the blocks on disk, the link count, the size.

That indirection is the whole game. Two processes can hold descriptors onto the same inode with independent offsets. A descriptor can point at an inode whose link count has dropped to zero — the file has no name anymore, ls cannot see it, but the blocks stay allocated until the last descriptor closes. And a socket has an open file description with no inode path at all, which is why lsof prints an address in the NAME column instead of a filename.

How lsof maps a process file descriptor to a kernel open file entry and then to an inode, including a deleted file whose blocks stay allocated

Read it left to right: lsof walks every process, reads every descriptor, resolves what it points at, and prints one row per descriptor. Everything else is filtering.

Step-by-step

1. Find what is listening on a port. This is the most common reason anyone opens lsof. -i selects internet files, and :443 narrows to that port:

sudo lsof -n -P -i :443
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   1412     root    6u  IPv4  28911      0t0  TCP *:443 (LISTEN)
nginx   1413 www-data    6u  IPv4  28911      0t0  TCP *:443 (LISTEN)
nginx   1413 www-data   12u  IPv4  91442      0t0  TCP 10.0.1.8:443->203.0.113.44:51022 (ESTABLISHED)

Always pass -n and -P. -n stops lsof from reverse-resolving every IP address to a hostname, and -P stops it from translating port numbers into service names from /etc/services. Without them, a busy server makes lsof sit there doing hundreds of DNS lookups before it prints anything. With them it returns immediately.

Note the shape of that output: the master nginx process listens as root, a worker inherited the same listening socket (same DEVICE, 28911), and the worker also holds an established connection to a client. Three rows, two processes, one port.

2. Decode the columns — especially FD. The FD column is where people get lost, because it holds two different kinds of value. Run lsof against a single process to see the full range:

sudo lsof -p 1413
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF   NODE NAME
nginx   1413 www-data  cwd    DIR  253,1     4096      2 /
nginx   1413 www-data  rtd    DIR  253,1     4096      2 /
nginx   1413 www-data  txt    REG  253,1  1355552 131441 /usr/sbin/nginx
nginx   1413 www-data  mem    REG  253,1   670744 137303 /usr/lib/x86_64-linux-gnu/libssl.so.3
nginx   1413 www-data    0r   CHR    1,3      0t0      5 /dev/null
nginx   1413 www-data    1w   REG  253,1  9118442 262401 /var/log/nginx/access.log
nginx   1413 www-data    2w   REG  253,1    41022 262402 /var/log/nginx/error.log
nginx   1413 www-data    6u  IPv4  28911      0t0    TCP *:443 (LISTEN)

The named codes are not descriptors at all — they are relationships the kernel tracks separately:

  • cwd — current working directory. This is why a shell sitting in a directory blocks umount.
  • rtd — root directory, normally /, different under chroot.
  • txt — the program text: the executable itself.
  • mem — a memory-mapped file, typically a shared library. Mapped, not held by a numbered descriptor.
  • DEL — a memory-mapped file that has since been deleted.

Numbered entries are real descriptors, and the letter suffix is the access mode: r read, w write, u read and write. So 0r is stdin open for read, 1w and 2w are stdout and stderr open for write, and 6u is a socket open read/write — sockets are almost always u.

The rest of the columns: TYPE is the kind of object (REG regular file, DIR directory, CHR character device, IPv4/IPv6 socket, FIFO pipe, unix domain socket). DEVICE is the device number for files or the kernel’s socket identifier. SIZE/OFF is the size for a file, or the offset shown as 0t0 for a socket. NODE is the inode number for files and the protocol for sockets. NAME is the resolved path or the socket address.

3. Ask broader socket questions. Every TCP listener on the machine, regardless of port:

sudo lsof -n -P -i TCP -sTCP:LISTEN
COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd      918     root    3u  IPv4  21044      0t0  TCP *:22 (LISTEN)
nginx    1412     root    6u  IPv4  28911      0t0  TCP *:443 (LISTEN)
postgres 1602 postgres    5u  IPv4  29155      0t0  TCP 127.0.0.1:5432 (LISTEN)

-sTCP:LISTEN filters by protocol state, and it takes the other states too: -sTCP:ESTABLISHED, -sTCP:CLOSE_WAIT. A pile of CLOSE_WAIT rows against one process is a strong hint that the application is not closing its sockets.

4. Watch out for the OR default. This is the single biggest gotcha in the tool. When you give lsof several selection options, it ORs them:

sudo lsof -u www-data -i

That does not mean “internet files belonging to www-data.” It means “everything owned by www-data, plus every internet file on the box.” Add -a to AND the selectors together:

sudo lsof -a -u www-data -i

Now it means what you thought it meant. Any time an lsof result looks suspiciously large, check whether you forgot -a.

5. Scope by user, command, or path. -u selects by user, and it accepts negation with ^:

sudo lsof -u postgres
sudo lsof -u ^root

-c selects by command name:

sudo lsof -c nginx

For files, pass a path directly to ask who has that exact file open:

sudo lsof /var/log/nginx/access.log
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF   NODE NAME
nginx   1412     root    1w   REG  253,1  9118442 262401 /var/log/nginx/access.log
nginx   1413 www-data    1w   REG  253,1  9118442 262401 /var/log/nginx/access.log

+D walks a whole directory tree, which is the answer to “what is keeping this mount busy?”:

sudo lsof +D /var/lib/mysql

+D is thorough but it stats every file underneath, so it is slow on a large tree. +d checks one level only. If you just need to unmount something, name the mountpoint instead — sudo lsof /mnt/data is far cheaper than descending it.

A map from common questions to the matching lsof invocation, covering ports, listeners, processes, paths, and deleted files

6. Find deleted files that are still eating disk. Here is the classic: df reports 96% full, you go hunting with du, and the numbers do not add up. Someone deleted a large log file while a process still had it open. The name is gone, so du cannot see it; the inode’s link count is zero but its blocks stay allocated until the descriptor closes. +L1 selects files with a link count below 1:

sudo lsof -n +L1
COMMAND    PID   USER   FD   TYPE DEVICE   SIZE/OFF NLINK   NODE NAME
java     22841 tomcat    3w   REG  253,1 3221225472     0 918274 /var/log/tomcat/catalina.out (deleted)

There it is: 3.2 GB, NLINK 0, still held by PID 22841 on descriptor 3. +L1 adds the NLINK column so you can see the link count directly. The clean fix is to restart or signal the process so it closes and reopens its log. If you cannot restart it right now, you can truncate the file through the descriptor the process is still holding:

sudo truncate -s 0 /proc/22841/fd/3

Space comes back immediately. This works for append-mode log files; do not do it to a database file or anything where a process tracks its own offset, because the offset will not move and the file will refill with sparse zeros. The durable fix is log rotation with copytruncate or a proper reopen signal. For the wider version of this hunt, see what to do when Linux says no space left on device.

7. Combine with kill. -t prints bare PIDs and nothing else, which is exactly what a pipeline wants:

sudo lsof -t -i :8080
31204
sudo kill $(sudo lsof -t -i :8080)

Look at the PIDs before you pipe them into kill. -t on a broad selector can return a lot of processes, and lsof -t +D /var piped into kill -9 is a genuinely bad afternoon.

Validate it works

Prove the model rather than trusting the flags. Open a file, delete it while it is still open, and watch the disk not come back:

python3 -c "f=open('/tmp/ghost.bin','wb'); f.write(b'x'*500000000); f.flush(); import os; os.unlink('/tmp/ghost.bin'); input('holding, press enter')" &

In another shell, the file has no name but the space is gone:

ls -l /tmp/ghost.bin
ls: cannot access '/tmp/ghost.bin': No such file or directory
sudo lsof -n +L1
COMMAND   PID     USER   FD   TYPE DEVICE  SIZE/OFF NLINK   NODE NAME
python3 41902 deploy      3w   REG  253,1 500000000     0 393221 /tmp/ghost.bin (deleted)

du -sh /tmp will not account for those 500 MB, but df -h /tmp will. Press enter to let the process exit, run df -h /tmp again, and the space returns — no rm required, because there was never a name left to remove. That is the entire deleted-file phenomenon in thirty seconds.

Troubleshooting

  • The output looks suspiciously short. You are not root. lsof cannot read /proc/<pid>/fd for processes you do not own, and it does not announce the omission — it just skips them. If a port is definitely bound but lsof -i :443 prints nothing, rerun with sudo before concluding anything. This is the failure mode that wastes the most time, because a partial answer looks exactly like a complete one.
  • df and du disagree and you cannot find the file. Deleted-but-open file, covered above. Go straight to sudo lsof -n +L1. If that comes back empty and the numbers still do not reconcile, the space is somewhere du cannot walk — most often a file hidden underneath a mountpoint, which you can check by bind-mounting the parent somewhere else and looking.
  • “Address already in use” but nothing appears to hold the port. First confirm with sudo lsof -n -P -i :8080 under root. If it is genuinely empty, the port is probably in TIME_WAIT from a previous process rather than held by a live one — there is no process to find, and the socket clears on its own. ss -tan | grep 8080 will show the TIME_WAIT entries lsof has nothing to report on. Setting SO_REUSEADDR in the application is the real fix.
  • lsof itself hangs. A dead NFS mount will block the kernel calls lsof makes, and lsof stops on the unreachable mount rather than finishing the scan. -b tells it to avoid any blocking kernel call, and -w suppresses the warnings that mode generates:
sudo lsof -b -w -n -P -i

You lose some detail for the paths it skipped, but you get output instead of a hung terminal.

  • lsof takes ten seconds to print anything. Missing -n and -P. Every remote address becomes a reverse DNS lookup and every port becomes an /etc/services lookup, serially, before the first row appears. On a server with hundreds of established connections this dominates the runtime completely. Make lsof -n -P -i your default and only drop the flags when you actually want the names resolved.
  • Too many rows to read. Combine -a with a narrow selector rather than grepping the output. Grep throws away the header, and it will happily match a PID against a byte offset in another column.

When this is the wrong approach

lsof is a broad, slow instrument that walks every process on the machine. It earns that cost when your question spans files and sockets, or when you do not yet know which of the two you are looking at. When the question is purely about sockets, ss -tulpn gives you the same listener answers from netlink in a fraction of the time and without root, and it is the tool to reach for by reflex; lsof -i is the fallback for when you also want that process’s open files in the same view. When the question is “what is this process doing right now” rather than “what does it hold,” lsof shows you a snapshot of state and nothing about behaviour — strace -p PID shows the actual syscalls, including the open() that is failing and the read() that is blocked. And if what you are chasing is descriptor exhaustion rather than a specific file, lsof -p PID | wc -l tells you the count but not the ceiling; see fixing too many open files and raising ulimits for the limits side of that problem. Full flag documentation lives in the lsof man page.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.