I set lsof linux to see in seconds which process is keeping which file, socket, or port open. That's how I identify blocked logs, occupied Ports and unlock blocked files without any detours, and resolve issues in a targeted manner.
Key points
To help you get started, I'll summarize the most important Aspects In a nutshell.
- Resources Make visible: processes, files, directories, devices, pipes, sockets.
- Filter Usage: by process name (-c), PID (-p), user (-u), file, directory (+d/+D), port (-i).
- Error Narrow down: Find locked files, resolve port conflicts, identify frozen services.
- Network Check: Quickly identify active connections and occupied ports.
- Workflow Streamline: First narrow down the options, then conduct a targeted review, and finally take action.
Why lsof Matters in Everyday Life
I use lsof, if a service fails to start, a file reports „busy,“ or a port is already in use. The tool links files, processes, users, and the network in a clear View. I can immediately see which PID is holding the lock and how long it’s been that way. This way, I take action instead of guessing, and I terminate the correct process instead of accidentally stopping the wrong service. Especially on production servers, this saves me minutes to hours because I can pinpoint the cause directly to the process. This approach reduces the number of support tickets, minimizes downtime, and creates a resilient Findings.
Understanding Basic Syntax and Output
The basic form is lsof [options] and returns all currently open items without any parameters properties. On heavily loaded systems, I filter the output instead of working my way through thousands of lines. It’s important to note that Linux defines „file“ broadly: this includes directories, devices, libraries, and network—Sockets. Columns such as COMMAND, PID, USER, FD, TYPE, and NAME are helpful in the output. I first look at FD (file descriptor), TYPE (REG, DIR, IPv4/6), and NAME, including the path or port information. By reading these columns, you can quickly understand the current system state and clearly map out the resources. Processes.
Installation and Permissions in Practice
On many distributions, lsof It is not preinstalled. So I'll install it early on using the package manager (apt install lsof, dnf install lsof, yum install lsof or pacman -S lsof), so that it's immediately available in the event of an incident. To get a complete picture, I usually run lsof with sudo because without elevated privileges, many entries result in a „permission denied“ error or are missing entirely. Nevertheless, I deliberately start without root access, see how far I can get, and only elevate privileges when necessary. On systems with SELinux or AppArmor, I keep in mind that security contexts can restrict visibility; depending on the build, lsof I also add contexts. I suppress warnings during bulk queries using -w, so that scripts remain robust.
Reading FD Fields and Types Safely
The Column FD is my key to understanding. Common values are:
cwd: the process's current working directory.txt: the executable file (text segment) of the process.mem: Loaded shared libraries and memory-mapped files.0h, 1w, 2w: Standard descriptors (stdin, stdout, stderr) with moder(read),w(write) oru(read/write).- higher numbers such as
3u,7r: regular open descriptors, often files, sockets, or pipes.
From TYPE I read the object class: REG (regular file), DIR (Directory), CHR/BLK (Drawing/Block Tool), first-in, first-out (Pipe), IPv4/IPv6 (Network), UNIX (Unix domain socket). In NAME the path, or in the case of sockets, the endpoint, e.g.,. TCP *:80 (LISTEN) or UDP 127.0.0.1:123. When I (deleted) When I look at the end, I can see that a file has been deleted but is still being held by a PID—a common reason for „missing“ disk space.
Targeted filtering: files, directories, ports
First, I'll define the context, and then I'll start with an appropriate Filter. For a directory, I use lsof +D /var/log (recursively) or lsof +d /var/log (just the folder itself). I check individual files directly, such as lsof /var/log/syslog, to view processes that are writing to disk. For ports, I set lsof -i:80, lsof -i:443 or generically lsof -i . I like to combine that with -nP, so that lsof doesn't resolve IP addresses and ports and runs faster. This transforms a confusing system state into a focused view in no time at all Image.
Combine and Refine Filters
To ensure repeatable analyses, I combine filters with -a logically linked. This way, I only get entries that meet all the conditions. Examples:
lsof -a -p 1234 -d cwd,txt,mem– Only a process's working directory, binary file, and loaded libraries.lsof -a -iTCP -sTCP:ESTABLISHED -p 1234– only established TCP connections for a given PID.lsof -a -u www-data +d /var/www– Files located under /var/www that keep processes belonging to the www-data user running.
With -d I filter by descriptors (numbers or names such as cwd, mem). -U It specifically includes Unix domain sockets in the output when I want to investigate local IPC issues. This way, I reduce noise and see exactly what's relevant to the issue.
Quickly Map Processes and Users
If I know a service name, it returns lsof -c nginx all open files on the web server, including Libraries, configurations, and sockets. To ensure a clear analysis, I often use the PID: lsof -p 1234 Displays all handles for a specific process. I perform user-related checks using lsof -u mysql or another account to make the resources opened by a service account visible. In more extensive analyses, I supplement the process view with Process Accounting and see how often and for how long programs use resources. This combination of process, user, and activity views helps me quickly get to the bottom of tricky issues Cause.
Special Cases: Deleted Files, Logrotate, and Space-Hogging Files
When there's a „shortage“ of disk space, I often find the cause by lsof +L1: It lists files that have already been deleted but are still being held open by processes. Typical examples include rotated logs, large temporary files, or debug dumps. Instead of frantically resizing the partition, I specifically terminate the displayed PIDs or send the usual signal to trigger a reload. For log services, I prefer to perform a clean reload of the respective service so that descriptors are reopened. Workarounds such as truncate Or, removing it directly without restarting the process will only postpone the problem.
For long data streams, I also check the column SIZE/OFF (visible depending on the build) to determine whether a process is hanging on a very large offset. This explains why a handle takes up so much memory even though the file is marked as deleted.
Systematically Resolving Typical Error Scenarios
I delete locked files after lsof has shown me the relevant process. Instead of stopping services haphazardly, I specifically terminate the PID or restart that exact service. I resolve port conflicts by lsof -i:, check the binding PID and then adjust the port, service, or firewall accordingly. If a process is hung, I check its open descriptors with lsof -p and determine whether it is waiting for a file, pipe, or socket. For in-depth analysis, I supplement the view with Targeted strace, to monitor system calls in real time. This allows me to reliably resolve recurring issues and document the steps needed to fix them for future Incidents.
Take containers and namespaces into account
Explained in containerized setups (e.g., with their own network namespaces) lsof I encounter inconsistencies between the host and the container. I either run `lsof` directly inside the container or enter the target process’s namespace from the host. This helps me understand why a port in the container is in the LISTEN state but appears „free“ on the host: they are in different namespaces. I take a similar approach with mount namespaces: Bind mounts and overlay file systems appear in the NAME column with their actual paths, helping me identify incorrectly configured volumes. I also organize open descriptors by user and cgroup when I manage services via supervisors or orchestration solutions.
Network Analysis with lsof -i
With lsof -i I detect active connections and listen for occupied ones Ports. Filters such as lsof -iTCP -sTCP:LISTEN List specific services in the LISTEN state. For individual protocols, I use lsof -iUDP or specific ports such as lsof -i:25 for mail servers. I also check whether a PID has multiple sockets open, which could indicate leaks or infinite loops. During security checks, I compare expected services with the output and identify unfamiliar or forgotten Services. This network view saves time because I don't have to check multiple tools at the same time and can see everything in one place.
Learn More About Network Details
For highly targeted queries, I use the address and port syntax from -i: I'm filtering by source or destination addresses (lsof [email protected]) or combine the address and port (lsof [email protected]:443). With -sTCP:ESTABLISHED I see productive sessions, while -sTCP:LISTEN only outputs listeners. I use UDP analysis to identify services with many short-lived sockets (DNS, Syslog, NTP). I also check whether processes are exposed on the network more than necessary (e.g., listeners on 0.0.0.0 (instead of a local interface). This reduces the amount of hardening work required later on.
Table Overview: Common Options
I use a few core options very regularly and customize them depending on Scenario. The following table lists the most important switches, along with a brief explanation and an example. This helps me find the right format more quickly and saves me from having to read through lengthy help sections. I apply these options in a modular way, which allows me to remain flexible. Once you’ve mastered this basic set, you can solve many problems with a single appeal.
| Option | Purpose | Example |
|---|---|---|
| -i | Show network connections and occupied ports | lsof -i:443 |
| -c NAME | Filter by process name (prefix match) | lsof -c nginx |
| -p PID | All open files associated with a PID | lsof -p 1234 |
| -u USER | A User's Open Resources | lsof -u mysql |
| +d DIR | Only the specified directory | lsof +d /var/log |
| +D DIR | Recursively through the directory | lsof +D /var/log |
| -nP | No DNS or port name lookup (faster) | lsof -nP -i |
| -t | Output only PIDs (script-friendly) | lsof -t -i:80 |
| +L1 | Show Deleted but Still Open Files | lsof +L1 |
I use -t often used to pass PIDs directly to scripts, such as to kill or systemctl. With +L1 I find processes that keep deleted files open and thus take up disk space. In combination with -r (repeat) I notice changes in short Distances. By testing step by step, you can avoid misinterpretations and ensure consistency in your work. This way, the diagnosis remains reproducible and measurable clear.
Process the output efficiently
I'll format the output right away so I can get results faster use. With lsof -t -i:80 | xargs -r kill -TERM I'll terminate all processes that are using port 80. For reports, I use lsof -nP -i | grep LISTEN Go back and filter specific states. Also awk helps: lsof -nP | awk '{print $1,$2,$3,$9}' Limits the view to name, PID, user, and path. I document one-liners that work and save myself the trouble later Search based on suitable patterns. Little helpers like watch 'lsof -nP -i:443' show changes in real time and lead to faster decisions.
Automation and parsable output
For recurring tests, I use the machine-readable version of lsof with -F. I select only the fields I need (e.g., process, command, user, FD, name) and continue parsing them reliably. Examples:
lsof -Fn -Fp -Fc -Fu -t -i:443– Minimalist fields for scripts that only require PIDs or names.lsof -Fpcun -a -iTCP -sTCP:LISTEN– Collect listener data and analyze it in a targeted manner.
With -r 2 I generate a „live“ view every two seconds and compare snapshots. In pipelines, I merge changes (sort, uniq, diff), to detect new or disappearing handles. I intentionally set timeouts so that queries don't get stuck under heavy load and monitoring jobs terminate cleanly.
Best Practices and Security Considerations
I run analyses with minimal permissions and only upgrade them when necessary root, if I don't have the necessary permissions. That way, I minimize risks and keep my logs clear. I run regular scans with lsof -i to detect unusual listeners or connections in my expected services. I then investigate suspicious PIDs by examining files, libraries, and Sockets. During maintenance windows, I make sure that no deleted but still open files are wasting space. Anyone who takes security seriously incorporates lsof into checklists and responds to anomalies with fixed Steps.
Common Pitfalls and Clean Solutions
- Not all entries are visible: Without root access, I often miss processes from other users or kernel-level handles. I specifically use
sudo. - Slow output: I disable resolutions using
-nP, avoid recursion and limit it with-ahard. - +D Too expensive: Recursive directory traversals can be huge. I'll start with
+dor specific paths, and expand them only as needed. - Port occupied, situation unclear: I combine
lsof -i: -nPwith-tfor PID and go tolsof -pdeeper. - „There is a lack of “open" space:
lsof +L1Finds open but deleted files. Then restart or shut down the process as needed. - Containers/Namespaces: I check the query in the correct namespace; otherwise, I might see the wrong listeners or overlook open files.
Understanding Performance and Limits
On very large systems, a full lsof scan takes time and causes noticeable Load. That's why I apply filters early on and switch to -nP all resolutions. When there are a large number of handle values, I check the File Descriptor Limits and increase them if necessary. Scripts should account for timeouts and use -t I only pass along PIDs to keep data volumes small. I document exceptions and incorporate recurring checks into my automation workflows. This ensures that diagnostics remain reliable and clear even under heavy load. controllable.
Practice workflow: From symptom to cause
I'll start with the question: Is this about a file, a process, or Port? Then I choose the appropriate opening, such as lsof /path/to/file, lsof -p or lsof -i:. I check USER, FD, TYPE, and NAME, and note what seems expected and what comes as a surprise. Then I take action: restart the process, adjust the configuration, raise the limit, or open the port. If I’m unsure, I freeze the current state, save the logs, and repeat the measurement after making the change. This process keeps me focused and provides a clear Chain of evidence.
Checklist: Quick Recipes for Everyday Meals
- Who is blocking the file?
lsof /path/to/file– Read the PID, then restart or terminate the process as needed. - Which service is using the port?
lsof -nP -i:– Resolve the conflict; adjust the port or bind address. - Where is the parking lot going?
lsof +L1– Find open or deleted files; restart the associated PIDs. - Is the process blocked by I/O?
lsof -p– Check for pipes, sockets, or files; use `strace` if necessary. - Which listeners are actually running?
lsof -nP -iTCP -sTCP:LISTEN– Compare with the list of expectations. - What resources does a service account use?
lsof -u– Identify anomalies per account.
A Quick Guide for Everyday Life
lsof shows me who is blocking which file, directory, or port. With -c, -p, -u, +d/+D and -i I quickly narrow down the scope. I unlock locked files, identify port conflicts, and detect unusual Connections. In combination with -nP I work quickly and keep the output manageable. For more in-depth analyses, I supplement my workflow with tools, document working one-liners, and incorporate recurring checks into automations. This keeps the diagnosis with lsof straightforward, reliable, and measurable. effectively.


