lsof Command in Linux: List Open Files and Network Sockets
Learn lsof command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
11 min read
Learn lsof command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What lsof Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Mastering the lsof command in linux unlocks one of the most powerful diagnostic capabilities in the Unix system administration toolkit. Rooted in the Unix philosophy that 'everything is a file,' the Linux kernel treats disk files, directories, character and block devices, named pipes (FIFOs), shared memory segments, Unix domain sockets, and internet network connections as open file descriptors referenced within process memory tables.
The lsof command in Linux (list open files) displays detailed information about all files, directories, character/block devices, shared libraries, and network sockets currently held open by active operating system processes. System administrators use lsof to identify which daemon is listening on a specific network port, discover which process is preventing a filesystem from unmounting, and recover disk space consumed by deleted open files.
Originally developed by Victor A. Abell at Purdue University, lsof serves as a master key for answering challenging operational questions: Why does umount report 'target is busy'? Which process is listening on TCP port 8080? Why does df report a full disk when du shows gigabytes of free space? By inspecting the kernel's active file descriptor tables, lsof surfaces the exact processes, user accounts, and file paths involved.
Unlike specialized networking tools like ss or netstat—which focus on transport-layer protocol state machines—lsof connects network sockets directly to the process tree, showing the Process ID (PID), process name, file descriptor number (FD), and user ownership for every open socket.
What lsof Does and When to Use It
At the operating system level, the Linux kernel tracks open files using three interconnected data structures: the per-process file descriptor table (struct files_struct), the system-wide open file table (struct file), and the Virtual File System inode table (struct inode). When an application invokes open(2) or socket(2), the kernel allocates an integer file descriptor within the process and points it to an entry in the system-wide file table.
To reconstruct this global mapping, lsof inspects the /proc virtual filesystem, examining /proc/[pid]/fd/* symbolic links, /proc/[pid]/maps memory mappings, and /proc/net socket tables. For network sockets, lsof correlates socket inode numbers (such as socket:[18420]) with entries in /proc/net/tcp and /proc/net/udp, resolving transport protocol, local/remote IP endpoints, and socket states (LISTEN, ESTABLISHED). In addition, lsof uses the +L1 option to discover unlinked files—files whose directory entries were removed via unlink(2) but whose disk blocks remain allocated because a running process still holds an open file descriptor.
At the operating system level, lsof interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running lsof in cloud instances or Kubernetes worker nodes, combining flags such as -i [SPEC], -p PID, -u USER, -c COMMAND lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.
Availability and Installation Across Linux Distributions
The lsof utility is packaged in lsof across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether lsof is installed and inspect which binary path and version your shell resolves:
type -a lsof
lsof --version 2>/dev/null || man -f lsof
# Illustrative output (reviewed against documentation)
lsof is /usr/bin/lsof
lsof (lsof)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y lsof
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y lsof
# Arch Linux
sudo pacman -S --noconfirm lsof
# Alpine Linux
sudo apk add --no-cache lsof
Command Syntax, Arguments, and Exit Status Codes
lsof [OPTIONS] [NAMES]
The command syntax follows: lsof [OPTIONS] [NAMES]. When invoked without arguments, lsof lists every file held open by every active process on the system (which can produce tens of thousands of lines). You typically supply filter flags: -i to filter by network socket, -p to filter by PID, -u to filter by username, -c to filter by command name, or +D to search a directory hierarchy.
Crucially, lsof uses OR logic by default when multiple selection flags are provided (for example, lsof -u www-data -i :80 lists files owned by www-data OR open on port 80). To enforce AND logic across all specified filters, you must supply the -a (AND) option: lsof -a -u www-data -i :80. Use -n to disable DNS lookups and -P to disable port name translation for maximum execution speed.
0— Successful execution; one or more matching open files or network sockets were found.1— No matching open files were found, or an operational error (such as insufficient permissions) occurred.2— Command-line syntax error or invalid argument supplied.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-i [SPEC] | --internet | Selects Internet and network files (e.g., -i TCP:80, -i :443, -i @192.0.2.10, or -i 4 for IPv4). |
-p PID | --process | Selects files opened by the specified Process ID (or comma-separated list of PIDs). |
-u USER | --user | Selects files opened by the specified login name or numeric User ID (UID). |
-c COMMAND | --command | Selects files opened by processes whose command name begins with the string COMMAND. |
-a | --and | ANDs all selection options together instead of using default OR logic. |
-t | --terse | Terse output; produces only Process IDs (PIDs) with no headers, ideal for piping to kill or xargs. |
+D DIR | +D | Recursively searches for all open files within the directory tree rooted at DIR. |
+L1 | +L1 | Lists deleted (unlinked) files with link counts less than 1 that are still held open in memory. |
-n -P | -n -P | Disables reverse DNS resolution of hostnames (-n) and port name service translation (-P). |
When inspecting network sockets with lsof, always combine -i with -n and -P (e.g., sudo lsof -i :80 -n -P). Without -n and -P, lsof performs reverse DNS lookups on every connected IP and queries /etc/services for port names, which causes noticeable latency on active production servers.
The -a (AND) flag is the most important conditional modifier in lsof. If you want to find open network sockets belonging strictly to a specific process (such as Nginx), running sudo lsof -c nginx -i without -a will list all files opened by Nginx PLUS all network sockets on the entire system. Running sudo lsof -a -c nginx -i properly restricts the output to Nginx's network sockets only.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Find Which Process Is Listening on a Specific Network Port
Identify the exact application daemon, PID, and user account bound to TCP port 80.
sudo lsof -i :80 -n -P
# Illustrative output (reviewed against documentation)
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 1250 root 6u IPv4 24120 0t0 TCP *:80 (LISTEN)
nginx 1251 www-data 6u IPv4 24120 0t0 TCP *:80 (LISTEN)
nginx 1252 www-data 6u IPv4 24120 0t0 TCP *:80 (LISTEN)
The output identifies Nginx master (PID 1250) and workers (PIDs 1251-1252) bound to port 80 across all interfaces (LISTEN state).
2. List All Network Sockets Belonging to a Specific Process
Use the -a flag to combine command name filtering with network socket selection.
sudo lsof -a -c sshd -i -n -P
# Illustrative output (reviewed against documentation)
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
sshd 842 root 3u IPv4 18420 0t0 TCP *:22 (LISTEN)
sshd 842 root 4u IPv6 18422 0t0 TCP *:22 (LISTEN)
sshd 2104 root 4u IPv4 42100 0t0 TCP 192.0.2.10:22->198.51.100.45:52341 (ESTABLISHED)
Combining -c sshd and -i with -a filters exclusively for OpenSSH sockets, revealing listening ports and an active client session.
3. Find All Open Files Within a Directory or Mount Point
Identify all processes keeping a filesystem busy when umount fails with 'target is busy'.
sudo lsof +D /var/log
# Illustrative output (reviewed against documentation)
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
rsyslogd 780 root 7w REG 8,1 452100 134210 /var/log/syslog
rsyslogd 780 root 8w REG 8,1 124500 134211 /var/log/auth.log
nginx 1251 www-data 4w REG 8,1 1842100 134215 /var/log/nginx/access.log
The +D option traverses /var/log recursively, pinpointing rsyslogd and Nginx as the processes actively writing to files.
4. List All Open Files Held by a Specific Process ID
Inspect all open file descriptors, shared libraries, and sockets owned by a specific daemon PID.
sudo lsof -p 1250
# Illustrative output (reviewed against documentation)
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 1250 root cwd DIR 8,1 4096 2 /
nginx 1250 root rtd DIR 8,1 4096 2 /
nginx 1250 root txt REG 8,1 1420120 1048210 /usr/sbin/nginx
nginx 1250 root mem REG 8,1 2048120 1048215 /lib/x86_64-linux-gnu/libc.so.6
nginx 1250 root 6u IPv4 24120 0t0 TCP *:80 (LISTEN)
nginx 1250 root 7u IPv4 24122 0t0 TCP *:443 (LISTEN)
The output reveals the working directory (cwd), root directory (rtd), executable text binary (txt), mapped shared libraries (mem), and listening socket descriptors.
5. Identify Deleted Unlinked Files Still Consuming Disk Space
Find large log files that were deleted via rm but are still held open by a process, preventing the kernel from reclaiming disk space.
sudo lsof +L1
# Illustrative output (reviewed against documentation)
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NLINK NODE NAME
app-srv 4210 root 3w REG 8,1 8421000000 0 1048590 /var/log/app.log (deleted)
The +L1 option lists files with link count 0 (deleted). Process app-srv (PID 4210) holds an 8.4GB log file open; restarting the service reclaims the disk space.
6. Output Only Process IDs (PIDs) for Piping to Kill
Extract only the PIDs associated with an open port using terse mode (-t) for clean pipeline automation.
sudo lsof -t -i :3000
# Illustrative output (reviewed against documentation)
4821
The -t flag suppresses all column headers and metadata, printing only the raw numeric PID (4821) suitable for command substitution: kill -9 $(sudo lsof -t -i :3000).
Real-World Workflows, Pipelines, and Shell Automation
Safe Filesystem Unmounting and Process Eviction Pipeline
When attempting to unmount a storage volume or USB drive (umount /mnt/data) fails with 'target is busy', identify locking processes, notify users, and gracefully unmount.
#!/usr/bin/env bash
set -euo pipefail
MOUNT_POINT="/mnt/data"
echo "=== Checking for Processes Locking: ${MOUNT_POINT} ==="
LOCKING_PIDS=$(sudo lsof -t +D "${MOUNT_POINT}" || true)
if [ -z "${LOCKING_PIDS}" ]; then
echo "No processes locking ${MOUNT_POINT}. Safe to unmount."
sudo umount "${MOUNT_POINT}"
echo "Unmount successful."
exit 0
fi
echo "The following processes are holding open files on ${MOUNT_POINT}:"
sudo lsof +D "${MOUNT_POINT}"
echo "Attempting graceful SIGTERM termination of locking processes..."
echo "${LOCKING_PIDS}" | xargs -r sudo kill -15
sleep 2
# Check if any processes survived SIGTERM
REMAINING_PIDS=$(sudo lsof -t +D "${MOUNT_POINT}" || true)
if [ -n "${REMAINING_PIDS}" ]; then
echo "Forcefully terminating stubborn processes with SIGKILL..."
echo "${REMAINING_PIDS}" | xargs -r sudo kill -9
sleep 1
fi
sudo umount "${MOUNT_POINT}"
echo "Filesystem ${MOUNT_POINT} unmounted successfully."
# Illustrative output (reviewed against documentation)
=== Checking for Processes Locking: /mnt/data ===
The following processes are holding open files on /mnt/data:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
backup 5120 admin 3r REG 8,2 14201000 12 /mnt/data/archive.tar
Attempting graceful SIGTERM termination of locking processes...
Filesystem /mnt/data unmounted successfully.
This production workflow uses lsof +D to find locking processes, attempts graceful termination, falls back to SIGKILL if necessary, and cleanly unmounts the volume.
Detecting and Reclaiming Hidden Disk Space from Deleted Files
Solve the classic sysadmin mystery where df reports 100% disk usage but du cannot find large files by identifying and remediating unlinked open files.
#!/usr/bin/env bash
set -euo pipefail
echo "=== Searching for Deleted Files Held Open in Memory (+L1) ==="
DELETED_FILES=$(sudo lsof +L1 -F nspct || true)
if [ -z "${DELETED_FILES}" ]; then
echo "No unlinked files held open by processes."
exit 0
fi
sudo lsof +L1 | awk '
NR==1 {print; next}
$7 > 100000000 { # Files larger than 100MB
printf "%-10s %-7s %-10s %-10s %-12s %s\n", $1, $2, $3, $4, ($7/1024/1024)"MB", $9;
}
'
echo "Remediation: Restart the offending processes or truncate descriptors via /proc/[pid]/fd/[fd]."
# Illustrative output (reviewed against documentation)
=== Searching for Deleted Files Held Open in Memory (+L1) ===
COMMAND PID USER FD SIZE NAME
node-app 3410 deploy 2w 1250MB /var/log/node-app.log
Remediation: Restart the offending processes or truncate descriptors via /proc/[pid]/fd/[fd].
The script searches for files with zero hard links (+L1), filters for files exceeding 100MB, and identifies node-app as the daemon holding 1.25GB of deleted logs in memory.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding lsof inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
The lsof command is strictly a read-only diagnostic reporting utility. However, piping terse output directly to kill commands (e.g., kill -9 $(sudo lsof -t -i :port)) without verifying the target PID can accidentally terminate critical infrastructure services or database engines.
Running lsof as an unprivileged user displays only files and network sockets opened by processes owned by that user. All files and sockets owned by root, system daemons, or other users are omitted. Administrative auditing requires root privileges or the CAP_SYS_PTRACE and CAP_DAC_READ_SEARCH capabilities.
In hardened environments with grsecurity or kernel ptrace_scope restrictions (kernel.yama.ptrace_scope = 1 or higher), unprivileged users cannot inspect the file descriptor tables of other processes even within the same group.
GNU/Linux, BSD, and BusyBox Implementation Differences
The lsof utility is widely available across Unix-like systems, including Linux, FreeBSD, OpenBSD, NetBSD, Solaris, AIX, and macOS. While core options (-i, -p, -u, -c, -t) are portable, kernel-specific options (such as +L1 for deleted files) rely on VFS semantics specific to each operating system.
On modern Linux systems, lsof is packaged in the lsof package across Debian, Ubuntu, RHEL, Fedora, Arch, and Alpine Linux. In minimal embedded environments, BusyBox does not include a full lsof implementation; administrators must inspect /proc/[pid]/fd directly.
Troubleshooting Common Errors and Diagnostics
lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
Root Cause: The FUSE user-space filesystem driver prevents other users (including root) from stat'ing mounted filesystems by default.
Resolution: Pass the -e option or ignore the warning, or unmount the stale FUSE mount using fusermount -u.
sudo lsof -b -i :80
lsof command hangs or executes very slowly
Root Cause: lsof is performing reverse DNS lookups on public IP addresses or query lookups on NFS/network-mounted filesystems that are unresponsive.
Resolution: Add the -n (no DNS) and -P (no port names) options, and use -b to avoid blocking on hung network filesystems.
sudo lsof -b -n -P -i
Incomplete output showing only your own processes
Root Cause: The command was executed without administrative privileges, preventing lsof from reading /proc entries belonging to other users.
Resolution: Rerun the command with sudo to inspect system-wide process file descriptors.
sudo lsof -i -n -P
Alternatives, Related Commands, and Related Tutorials
- How to Check Open Ports in Linux: nmap, netcat, and Bash — Practical syntax, flags, and examples for
nc. - ss Command in Linux: Display Socket Statistics and Listening Ports — Practical syntax, flags, and examples for
ss. - netstat Command in Linux: Network Connections, Routing, and Statistics — Practical syntax, flags, and examples for
netstat. - Netcat (nc) Command in Linux: Port Scanning, Transfers, and Debugging — Practical syntax, flags, and examples for
nc. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides


Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!