lsof - Linux


Overview

The lsof command in Linux stands for “List Open Files”. This tool is used to display information about files opened by processes. An open file may be a regular file, a directory, a block device, a network file system, or a named pipe. lsof is extremely useful for system administrators for troubleshooting and monitoring the system, especially to identify files that are in use by processes.

Syntax

The basic syntax of the lsof command is:

lsof [options] [names]

Where options are the flags that control the output, and names can be a list of specific files, directories, or processes to inspect.

Options/Flags

  • -i [selector]: Select files based on network or network-like files parameters. The selector can be protocol, such as tcp or udp, or a port number.
  • +D <dir>: List all files within a directory recursively.
  • -u <user>: List files opened by the specified user.
  • -p <PID>: Only show files opened by the given process ID. Multiple -p flags can be used.
  • -t: Produces a bare output with just process IDs, useful for scripting.
  • -c <cmd>: List files opened by processes named <cmd>.
  • -d <fd>: Show information for the specified file descriptor <fd>.
  • -a: Combines filters with an AND condition rather than the default OR.

Examples

  1. List all open files by user ‘john’:
    lsof -u john
    
  2. Find which process is using port 80:
    lsof -i :80
    
  3. List files opened by process with PID 1234:
    lsof -p 1234
    
  4. List all network files used by SSH:
    lsof -c ssh -i
    
  5. List all files opened in a directory, including subdirectories:
    lsof +D /path/to/directory
    

Common Issues

  • Permission Denied: Running lsof without sufficient permissions (root) may result in partial or no data. Use sudo to run lsof for comprehensive system-wide information.
  • Performance Impact: On a system with a large number of open files, lsof can be slow and consume considerable resources. Use specific options to narrow down the search.

Integration

Combine lsof with other commands to perform advanced filtering and scripting. For example:

  • Kill all processes that are using a specific file:

    kill $(lsof -t /file/to/kill)
    
  • Check open files and sort by decreasing size:

    lsof /some/path | awk '{print $7, $9}' | sort -rn
    
  • netstat: Shows network connections, routing tables, and a number of network interface statistics.
  • fuser: Identifies processes using files or sockets.
  • ps: Provides information about currently running processes.

For further reading and more detailed information, consult the lsof man page or the official Lsof FAQ.

By understanding and utilizing lsof, system administrators can effectively manage and troubleshoot various system-related issues, enhancing both system performance and security.