lsof Command

The lsof command (list open files) displays information about files opened by processes. In Unix-like systems, everything is treated as a file, so lsof shows regular files, directories, network sockets, pipes, and other file descriptors.

Syntax

lsof [OPTIONS] [FILES...]

Description

The lsof command is a powerful diagnostic tool that lists information about files opened by processes. It can show regular files, directories, network connections, pipes, and other file descriptors.

Key features:

  • List all open files on the system
  • Show files opened by specific processes
  • Display network connections and listening ports
  • Find processes using specific files or directories
  • Monitor file system usage
  • Troubleshoot "device busy" errors
Note: lsof requires root privileges to show information about all processes. Regular users can only see their own processes.

Common Options

Option Description
-a AND the selections (default is OR)
-c command List files opened by processes with specified command name
-d fd List files with specified file descriptor
-i [protocol][@host][:port] List network connections (Internet files)
-n Don't resolve hostnames (show IP addresses)
-P Don't resolve port names (show port numbers)
-p PID List files opened by specific process ID
-t Terse output (PIDs only)
-u user List files opened by specific user
-r [time] Repeat mode (refresh every time seconds)
+D directory Search directory tree for open files
+d directory Search directory (not subdirectories) for open files

Examples

List all open files

lsof

Display all open files on the system (requires root for complete output)

List files opened by a specific process

lsof -p 1234

Show all files opened by process with PID 1234

List files opened by a command

lsof -c firefox

Show files opened by all Firefox processes

List network connections

lsof -i

Display all network connections and listening ports

List specific port connections

lsof -i :80 lsof -i :22 lsof -i tcp:443

Show connections on specific ports

List files opened by a user

lsof -u username

Show all files opened by a specific user

Find processes using a file

lsof /path/to/file

Show which processes have the specified file open

Find processes using a directory

lsof +D /home/user

Show processes using files in the directory tree

Understanding lsof Output

Output Columns

Column Description
COMMAND Process command name (first 9 characters)
PID Process ID
USER User who owns the process
FD File descriptor (cwd, txt, mem, or number)
TYPE File type (REG, DIR, CHR, BLK, FIFO, IPv4, IPv6)
DEVICE Device numbers or protocol
SIZE/OFF File size or offset
NODE Inode number or protocol-specific identifier
NAME File name or network address

File Descriptor Types

FD Value Description
cwd Current working directory
txt Program text (executable)
mem Memory-mapped file
rtd Root directory
0 Standard input
1 Standard output
2 Standard error
3+ Other file descriptors

Example Output

$ lsof -p 1234 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME firefox 1234 user cwd DIR 8,1 4096 2097153 /home/user firefox 1234 user txt REG 8,1 98234567 1048577 /usr/bin/firefox firefox 1234 user 0u CHR 1,3 0t0 1028 /dev/null firefox 1234 user 1u CHR 1,3 0t0 1028 /dev/null firefox 1234 user 2u CHR 1,3 0t0 1028 /dev/null firefox 1234 user 3u IPv4 12345 0t0 TCP *:8080 (LISTEN)

Example lsof output showing different file types and descriptors

Network Monitoring

Basic Network Commands

All network connections

lsof -i

Show all network connections (TCP and UDP)

TCP connections only

lsof -i tcp

Show only TCP connections

UDP connections only

lsof -i udp

Show only UDP connections

Listening ports

lsof -i -sTCP:LISTEN

Show only listening TCP ports

Established connections

lsof -i -sTCP:ESTABLISHED

Show only established TCP connections

Specific Port Monitoring

Web server ports

# HTTP lsof -i :80 # HTTPS lsof -i :443 # Both HTTP and HTTPS lsof -i :80,443

Monitor web server connections

SSH connections

lsof -i :22

Show SSH connections

Database connections

# MySQL lsof -i :3306 # PostgreSQL lsof -i :5432 # MongoDB lsof -i :27017

Monitor database connections

Network Troubleshooting

Find process using a port

# Find what's using port 8080 lsof -i :8080 # Get just the PID lsof -t -i :8080

Identify processes using specific ports

Monitor connections without DNS resolution

lsof -i -n -P

Show connections with IP addresses and port numbers (faster)

Process Monitoring

Process File Usage

Files opened by specific process

# By PID lsof -p 1234 # By command name lsof -c apache2 # Multiple processes lsof -p 1234,5678

Monitor file usage by specific processes

User file usage

# All files opened by user lsof -u username # Exclude specific user lsof -u ^username # Multiple users lsof -u user1,user2

Monitor file usage by users

File System Monitoring

Files in directory

# Directory only lsof +d /var/log # Directory tree lsof +D /home/user

Find processes using files in directories

Specific file usage

# Single file lsof /var/log/syslog # Multiple files lsof /var/log/syslog /var/log/auth.log

Find processes using specific files

Troubleshooting "Device Busy" Errors

Find processes using a mount point

# Before unmounting lsof +D /mnt/usb # Kill processes if needed lsof -t +D /mnt/usb | xargs kill

Identify processes preventing unmount

Find processes using deleted files

lsof | grep "(deleted)"

Find processes holding references to deleted files

Advanced Usage

Combining Options

AND logic with -a

# Files opened by specific user AND command lsof -a -u username -c firefox # Network connections by specific process lsof -a -p 1234 -i

Combine multiple criteria with AND logic

Exclude criteria

# All users except root lsof -u ^root # All processes except kernel threads lsof -c ^kernel

Exclude specific criteria from results

Continuous Monitoring

Repeat mode

# Refresh every 2 seconds lsof -r 2 -i # Monitor specific process lsof -r 1 -p 1234 # Monitor network connections lsof -r 5 -i tcp

Continuously monitor file usage and connections

Terse output for scripting

# Get PIDs only lsof -t -i :80 # Kill processes using port 8080 kill $(lsof -t -i :8080) # Count open files by process lsof -p 1234 | wc -l

Use terse output for automation and scripting

Practical Use Cases

System Administration

Security monitoring

# Check for suspicious network connections lsof -i -n -P | grep ESTABLISHED # Monitor root processes lsof -u root -i # Check for unusual file access lsof +D /etc | grep -v "^COMMAND"

Monitor system security and detect anomalies

Performance troubleshooting

# Find processes with many open files lsof | awk '{print $2}' | sort | uniq -c | sort -nr | head -10 # Check file descriptor limits lsof -p 1234 | wc -l # Monitor memory-mapped files lsof -d mem -p 1234

Diagnose performance issues related to file usage

Development and Debugging

Application debugging

# Monitor application file usage lsof -c myapp # Check configuration file access lsof /etc/myapp/config.conf # Monitor log file writers lsof /var/log/myapp.log

Debug application file access patterns

Database troubleshooting

# Check database connections lsof -i :3306 -i :5432 # Monitor database file access lsof -c mysqld -c postgres # Find locked database files lsof +D /var/lib/mysql

Troubleshoot database connectivity and file locking

Network Administration

Port management

# Find available ports for port in {8000..8010}; do if ! lsof -i :$port > /dev/null 2>&1; then echo "Port $port is available" fi done # Check service ports lsof -i :80 -i :443 -i :22 -i :25

Manage port allocation and service monitoring

Connection analysis

# Analyze connection states lsof -i tcp | awk '{print $8}' | sort | uniq -c # Monitor foreign connections lsof -i tcp | grep -v localhost | grep -v 127.0.0.1 # Check connection counts by process lsof -i | awk '{print $1}' | sort | uniq -c | sort -nr

Analyze network connection patterns and states

Scripting Examples

System Monitoring Scripts

Port usage report

#!/bin/bash echo "=== Port Usage Report ===" echo "Listening ports:" lsof -i -sTCP:LISTEN -P -n | awk 'NR>1 {print $9, $1, $2}' | sort -n echo echo "Established connections:" lsof -i -sTCP:ESTABLISHED -P -n | wc -l echo echo "Top processes by connection count:" lsof -i | awk 'NR>1 {print $1}' | sort | uniq -c | sort -nr | head -5

Generate comprehensive port usage reports

File descriptor monitoring

#!/bin/bash echo "=== File Descriptor Usage ===" for pid in $(ps -eo pid --no-headers); do count=$(lsof -p $pid 2>/dev/null | wc -l) if [ $count -gt 100 ]; then cmd=$(ps -p $pid -o comm --no-headers 2>/dev/null) echo "PID $pid ($cmd): $count open files" fi done | sort -k4 -nr

Monitor processes with high file descriptor usage

Cleanup Scripts

Kill processes using specific files

#!/bin/bash FILE="$1" if [ -z "$FILE" ]; then echo "Usage: $0 " exit 1 fi echo "Processes using $FILE:" lsof "$FILE" read -p "Kill these processes? (y/N): " confirm if [ "$confirm" = "y" ]; then lsof -t "$FILE" | xargs kill echo "Processes killed" fi

Safely kill processes using specific files

Network connection cleanup

#!/bin/bash PORT="$1" if [ -z "$PORT" ]; then echo "Usage: $0 " exit 1 fi echo "Processes using port $PORT:" lsof -i :$PORT read -p "Kill processes using port $PORT? (y/N): " confirm if [ "$confirm" = "y" ]; then lsof -t -i :$PORT | xargs kill echo "Processes killed" fi

Clean up processes using specific network ports

Troubleshooting

Common Issues

Permission denied

# Run with sudo for complete system view sudo lsof # Regular users see limited information lsof -u $USER # Check what you can see without root lsof -p $$

Handle permission limitations

Performance with large systems

# Use specific criteria to limit output lsof -i -n -P # Faster network listing # Avoid DNS lookups lsof -n # Avoid port name resolution lsof -P # Target specific processes lsof -p $(pgrep apache2)

Optimize lsof performance on busy systems

Alternative Commands

When lsof is not available

# Check /proc filesystem ls -la /proc/1234/fd/ # Use netstat for network connections netstat -tulpn # Use ss for socket statistics ss -tulpn # Check process file descriptors cat /proc/1234/limits

Alternative methods when lsof is unavailable

Cross-verification

# Compare with netstat lsof -i :80 netstat -tulpn | grep :80 # Compare with ss lsof -i tcp ss -t -a # Verify process information lsof -p 1234 ls -la /proc/1234/fd/

Cross-verify lsof output with other tools

Best Practices

lsof Best Practices
  • Use Specific Criteria - Narrow down searches to avoid overwhelming output
  • Combine with Other Tools - Use with ps, netstat, and ss for comprehensive analysis
  • Script Automation - Use terse output (-t) for automated processing
  • Performance Optimization - Use -n and -P flags to avoid DNS/port lookups
  • Security Monitoring - Regularly check for unusual network connections
  • Resource Management - Monitor file descriptor usage to prevent exhaustion

See also