Back to Explore
GuideVibeFix editorialUpdated Dec 1, 2026

lsof From Zero: Who Holds the Port, Who Holds the File

lsof from zero: a 41-line transcript on lsof 4.95.0 uses an HTTP server on port 18741 and a process holding a file to cover -i port lookup, -sTCP:LISTEN, -p per-process listing, lsof file and +D directory, plus two real traps: no match exits 1 with zero output, which kills a set -e script, and a deleted file still shows as (deleted) with its disk space unreleased.

Real photograph of a row of server racks in a data centre (illustrative photo)

Everyone who troubleshoots Linux has hit the same two questions: "which process is holding this port?" and "which process has this file locked?" The answer to both is the same command: lsof, short for "list open files". On Linux, "everything is a file" is more than a slogan: network ports, directories, pipes and devices are all file descriptors behind the scenes. So lsof answers far more than "who opened this file": it can tell you which process listens on which port, everything a single process has open, and why a deleted file still eats disk space. This guide starts from zero, using one HTTP server and one process holding a file open, with 41 lines of tested output, to explain the everyday uses of lsof and two genuine traps: when nothing matches, it exits 1 with zero output, which kills a script written with set -e stone dead; and a deleted file does not free its disk space, with the line marked (deleted) in lsof as the evidence. Both traps were hit for real during the demo.

The demo environment first: lsof 4.95.0, Python 3.12.3, demo script demo274_lsof.sh, working directory /tmp/demo274-lsof-work, wiped and rebuilt on every run. The demo port is fixed at 18741. One processing detail needs stating up front: process IDs differ on every run, so to make the output reproducible byte for byte, the script replaces the PID column with the literal string PID and prints only the stable columns (command, PID, user, file descriptor, type, name). On your own machine you will see real PIDs instead — that is not an error, only the normalisation. The commands and the shape of the output are the same.

§0 First, start a server and a process holding a file

The demo needs two "suspects". The first is an HTTP server started with Python: python3 -m http.server 18741 --bind 127.0.0.1, listening on local port 18741 with the demo working directory as its root. The second is a Python process that opens held.log, writes 100 characters into it, and then sleeps for 60 seconds without letting go. One holds a port, the other holds a file — the two main jobs lsof exists for. One more detail: the working directory starts out holding index.html and held.log, the first for the HTTP server to serve, the second for the other process to hold.

Do not start querying yet. Remember the two roles: the HTTP server is the "port holder", the other process is the "file holder". Every section below uses lsof to answer a question about one of them. At the end of the demo, the script kills both processes, frees the port and deletes the working directory — the last of the 41 lines is "cleaned up".

§1 Who is using this port: lsof -i :port

The most common use is this one: lsof -i :18741. The demo output is just two lines: the header COMMAND PID USER FD TYPE NAME, then python3 PID root 3u IPv4 localhost:18741 (LISTEN). That one line carries a lot, column by column: python3 is the process name, PID is the normalised process ID, root is the user running it, 3u is the file descriptor number plus its read/write mode (descriptor 3, u for read-write), IPv4 is the socket type, and localhost:18741 (LISTEN) says it is listening on local port 18741.

Three spellings of the port query are worth separating. lsof -i :18741 means "who is using port 18741", regardless of TCP or UDP, listening or connected. lsof -i TCP:18741 means TCP only; lsof -i UDP:18741 means UDP only. You can also add -sTCP:LISTEN after the port, meaning "listening sockets only" — that gets its own section next. The most common real-world trigger is starting a service and being told the port is already in use; the first reflex should be lsof -i :port — see who it is first, then decide whether to kill it or pick another port.

§2 Listening sockets only: -sTCP:LISTEN

One port can hold a listening socket and established connections at the same time, and the mixed output is hard to read. Section §2 of the demo runs lsof -i TCP:18741 -sTCP:LISTEN, and the output is identical to §1: the same line, python3 PID root 3u IPv4 localhost:18741 (LISTEN). Same output, different meaning: §1 is "everything using this port", §2 is "listening on this port". The demo has one listening socket and no established connections, so the two sections agree; on a real service they would not — a web server might have one listening socket and hundreds of established connections, and -sTCP:LISTEN lets you see the listener at a glance instead of paging through hundreds of connections.

The -s flag takes more states than LISTEN. Use -sTCP:SYN-SENT for connections stuck in the handshake, and -sTCP:CLOSE_WAIT for connections that are half-closed. The one most worth remembering is CLOSE_WAIT: a socket sitting in CLOSE_WAIT for a long time usually means the program is not closing connections promptly, and the count will keep growing until file descriptors run out. When you see CLOSE_WAIT piling up, check the program first, then the lsof output — in that order.

§3 Trap 1: when nothing matches, lsof exits 1 with zero output

This is the first genuine trap in this guide. Section §3 of the demo runs lsof -i :19999, a port no process is using. The output is nothing at all — not even a header, just a line the script prints itself: exit=1. In other words, when lsof finds nothing, it prints no header and no message, and quietly exits with code 1. Exit 1 here means "no match", not "the command failed". That behaviour is fine on its own; the problem is what it does in combination with set -e.

The demo script starts with set -euo pipefail, the standard way to write a Bash script: any command that fails ends the whole script immediately. In the first draft of the demo, the lsof -i :19999 line had no protection, and the script died right there — none of the later sections printed a single line, and there was not even an error message, because lsof itself prints nothing. The behaviour is easy to reproduce with a three-line script: set -euo pipefail plus one line of lsof -i :19999, and the script exits quietly at that line with code 1. That is the bug caught for real in the demo: not a bug in lsof, but a collision between "no match exits 1" and "failure exits the script".

There are two fixes. One is to add || true to any lsof that might find nothing, meaning "even if it exits 1, carry on as if nothing happened" — that is what the final demo script does. The other is to test first and query second: wrap it in if lsof -i :port >/dev/null; then ... fi, treating "is there a process" as a condition rather than an error. Either way works. The rule to remember is this: exit 1 from lsof does not mean an error, it means "not found", and scripts must handle it as "not found", not as "failed".

§4 What one process has open: lsof -p PID

The other way round — you know the process and want to know what it has open — is lsof -p PID. Section §4 of the demo looks at the HTTP server process, and after filtering the output is four lines: cwd DIR /tmp/demo274-lsof-work (current working directory), rtd DIR / (root directory), txt REG /usr/bin/python3.12 (the program's own executable), and 3u IPv4 localhost:18741 (LISTEN) (the listening socket). Those four lines are a process's "holdings": where it runs, what program it is, and what it listens on.

The unfiltered output is much longer: besides those four lines, there are a dozen or so mem rows — memory maps of the shared libraries Python loads, such as libc.so.6 and libssl.so.3. The demo script filters them out deliberately, keeping only cwd, txt, rtd, IPv4, DIR and REG. Why drop mem? Because the shared-library list is long and almost never useful for troubleshooting — it buries the few lines that matter. When you look at what a process has open, the focus is always three things: working directory, the program itself, and network connections. Everything else is noise.

One subtlety worth flagging: lsof -p shows what a process has open right now, not what it has ever opened. A file that was opened, used and closed is invisible to lsof -p. For "what did this process open in the past", you need audit logs or strace — lsof cannot answer that. Its view is always "now", never "once".

§5 Who holds this file: lsof file and lsof +D directory

There are two ways to query a file. The first is to pass the path directly: lsof /tmp/demo274-lsof-work/held.log. The demo output is a single line: python3 PID root 3w REG /tmp/demo274-lsof-work/held.log. The holder process has the file open for writing (the w in 3w), and the type is a regular file (REG). When a file cannot be deleted, a disk fills up, or log rotation stalls, this is the first command to run: find out who holds it.

The second is lsof +D directory, meaning "list every open file under this directory". The demo runs lsof +D /tmp/demo274-lsof-work, and the output has eight lines: the two Python processes' cwd entries (both work in this directory), the holder's 3w REG held.log, and several cwd lines for lsof, awk and bash themselves — even lsof and the awk in the pipeline show up, because their working directory is this directory too. That is a telling detail: lsof counts itself when it enumerates. When reading +D output, first recognise lsof, awk and bash as "the investigators themselves"; what is left is the processes genuinely holding the directory.

Do not confuse +D with plain lsof directory: the latter only asks "who opened this directory itself", while lsof +D directory recursively asks "every open file under this directory". The first usually returns a few lines, the second can return hundreds. One performance warning: +D scans recursively, so the bigger the directory the slower it gets — running lsof +D / on a production machine can take a long time, so be careful.

§6 Trap 2: the file is deleted, the disk is not freed — (deleted)

This is the second genuine trap, and the most classic one. Section §6 of the demo deletes held.log first, then runs ls to confirm: the output is ls: cannot access '/tmp/demo274-lsof-work/held.log': No such file or directory, with exit code 2. The file is genuinely gone from the directory. But running lsof -p PID | grep deleted right after gives: python3 PID root 3w REG /tmp/demo274-lsof-work/held.log (deleted). The file has been deleted, yet the process still holds it, with a (deleted) marker hanging off the name.

The mechanism is how Linux filesystems work: deleting a file only removes its name from the directory. The file's data stays on disk as long as any process still has it open — the kernel will not release its space. In other words, rm removes the signpost, not the house; the house is still there, only unreachable. That is why a full disk stays full after deleting the biggest log file: the deleted log is still held by some process, and the space was never released. The right response is not to keep deleting files, but to find the holder — lsof | grep deleted — then restart that process or make it reopen its log file. Only then does the space actually come back.

One number from the demo is worth memorising: ls exits with code 2 when the file is not there, not 1. Put next to the lsof exit 1 from §3, it makes the point nicely: different commands use different exit codes for "not found". lsof's 1 means "no match"; ls's 2 means "no such file". In scripts, an exit code cannot be read as just "zero or not zero" — each command has its own convention, and the exact number matters.

§7 Numeric form: -n -P does not resolve names

By default, lsof resolves IP addresses to hostnames and port numbers to service names. The §1 output in the demo shows the listening address as localhost:18741 — localhost is the name resolved from 127.0.0.1. Section §7 runs the same command with -n -P added, and the output becomes 127.0.0.1:18741 (LISTEN): -n skips hostname resolution, -P skips port-name resolution, and the address is printed as plain numbers.

Each form has its use. For troubleshooting, -n -P is better, for two reasons: first, resolving names means DNS lookups, and a slow DNS makes lsof slow or even hang; second, numbers are unambiguous — 127.0.0.1 is 127.0.0.1, while localhost can point at different addresses on different machines. In scripts, always add -n -P — faster and steadier. When a human is reading the output, the default form is easier on the eyes, so leaving the flags off is fine. That small habit saves a lot of wondering why lsof is so slow.

§8 Wrapping up: kill the server, the port is free

The last section is the clean-up: kill the HTTP server and the file-holding process, then query port 18741 once more. The output is the same as §3: nothing at all, just exit=1 (port is free again). Same empty output, same exit 1, completely different meaning: the §3 emptiness meant "nobody ever used this port", while the §8 emptiness means "the user of this port has left". Reading lsof output needs context: empty output carries no information by itself — the information is in what you knew before.

The script does two more things at the end: it changes back to the root directory and deletes the demo working directory, and its last line reads "cleaned up". There is one more design detail in the demo script worth copying: at the top it registers a clean-up function with trap, so the two background processes are killed whether the script ends normally or dies halfway. That came from a real failure in the first draft: when the script died at the lsof -i :19999 line in §3, the HTTP server was left behind still holding port 18741, and the next run could not even bind. The lesson is that any script that starts background processes must use trap to guarantee they get cleaned up — otherwise one failure poisons every run after it.

§9 Three useful combinations: -t, -u, -c

Beyond the uses above, lsof has three options that come up constantly in troubleshooting. The first is -t, meaning "print only the process IDs, no header and no other columns". For example, lsof -t -i :18741 prints a single number: the PID listening on that port. That output is made for scripts: kill $(lsof -t -i :18741) kills the process holding the port in one line, with no awk needed to pick out the second column. The demo does not use -t, because it wants to show the full output; in real scripts, -t is the cleaner choice.

The second is -u, meaning "only processes belonging to this user". lsof -u root lists the files opened by root's processes. On a multi-user server, when the question is "who filled the disk", filtering by user first shrinks the search immediately. The third is -c, meaning "only processes with this command name" — lsof -c python3 lists what every process called python3 has open. Both combine with -i and -p, for example lsof -u root -i :18741, meaning "among root's processes, who is using port 18741". The pattern is always the same: narrow the scope first, then look at the details.

One last warning, about permissions: lsof can only see processes you have permission to see. Run as an ordinary user, it shows only your own processes' files; other users' processes are invisible. To see the whole system, run as root or with sudo. The demo ran as root throughout, so everything was visible. On your own machine, if lsof -i :port finds nothing, ask first whether it is a permission problem — many false "nobody uses this port" conclusions are permission problems in disguise. Checking who you are before querying saves more time than doubting the output afterwards.

Cheat sheet

Everything used in this guide, in one table for quick reference:

What you wantCommand
Who is using this portlsof -i :port
TCP listening sockets onlylsof -i TCP:port -sTCP:LISTEN
What one process has openlsof -p PID
Who holds this filelsof filepath
Every open file under a directorylsof +D directory
Deleted files still held openlsof | grep deleted
Numeric form, no name resolutionlsof -i :port -n -P
Only one user's processeslsof -u username
Only one command's processeslsof -c processname

How this guide relates to the neighbouring guides

This is a dedicated guide to lsof — who has what open. The guides it is easiest to confuse it with draw their lines here: the Linux process management guide covers the life cycle of processes — starting, stopping, checking status and resource usage — with the process itself as the subject; the Linux disk usage guide covers how much disk is used and how much is left, with the numbers from du and df as the subject; the Linux text processing guide covers how to filter the lines you want out of output, with tools like grep and sort as the subject; the rsync backup guide covers moving files from one machine to another, with synchronisation as the subject. This guide covers none of those — no process management, no disk statistics, no text filtering, no file syncing — only one thing: who is holding a given file or port. What to do once you know — killing the process, restarting the service, freeing the disk — belongs to the other guides.

How port, process and file relate: port 18741 belongs to the Python server, held.log belongs to the file-holding process, and after deletion it shows as (deleted)

Views 1Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photograph of a server room patch panel filled with blue network cables (illustrative photo)
Guide
ping From Zero: One Packet Tells You If It Is Alive — the Exit Code Matters More Than the Output

ping does exactly one thing: send an ICMP echo request, wait for the echo reply, and report the round-trip time and packet loss. This guide runs every command for real on iputils ping 20240117 — packet count, interval, quiet mode, packet size, timestamps, IPv4 vs IPv6, the three failure modes, exit codes 0/1/2 — with output pasted verbatim.

Developer WorkflowTool TipsDebugging
Real photograph of a wooden desk with a white alarm clock beside a calendar page (illustrative photo)
Guide
crontab From Zero: Jobs That Just Run on Time, Five Fields Explained Once

cron is the scheduling daemon that has run on Linux for decades: write a crontab file saying 'run this command at this time', and it handles the rest. This guide runs everything for real on Debian cron 3.0pl1-162 — installing a job, waiting one minute for the trigger, verifying the log, removing the job — plus special strings, five classic mistakes, and a real 3 a.m. log-archiving job.

Developer WorkflowAutomationTool Tips
Real photograph of scissors cutting a white sheet of paper on a white background (illustrative photo)
Guide
cut From Zero: Slicing Columns Out of Lines

cut does one thing: split each line into fields on a delimiter and output the fields you ask for. This guide runs every command for real on GNU coreutils 9.4 — field lists and ranges, CSV and output delimiters, character slicing, --complement, the -s rule for lines without a delimiter, log-column statistics, and the quoted-comma limit — with the output pasted verbatim.

Developer WorkflowTool TipsAI Coding