The lsof command in Linux: list open files by process

Introduction to lsof

The commandlsof(List Open Files) is an essential tool for Linux system administrators to see which files, devices, sockets and pipes have open each process in the system. This information is useful for purifying permit problems, detecting resource leaks or investigating suspicious activities.

Installation and availability

In most modern distributions,lsofcomes pre-installed. If not available, you can install it with the corresponding package manager:

  • Debian / Ubuntu:sudo apt-get install lsof
  • Hat / CentOS Network:sudo yum install lsof
  • Fedora:sudo dnf install lsof
  • Arch Linux:sudo pacman -S lsof

Basic syntax

The simplest way to runlsofis without arguments, which shows all files opened by all processes:

sudo lsof

Because the output can be very extensive, it is usually useful to combine it with filtering options or withgrep.

Most commonly used filtering options

  • -p <PID>: shows the files opened by the process whose ID is<PID>.
  • -u <usuario>: list the files opened by all specified user processes.
  • -i <condición>: filters network connections. For example,-i TCP:80shows the TCP sockets at port 80.
  • +D <directorio>: lists all open files within a directory and its subdirectories.
  • -d <descriptor>: limits output to certain types of file descriptors (e.g.,-d 1for stdout).
  • -t: only print the PID, useful to move to other commands likekill.
  • -F: produces a machine-readable output, ideal for scripts.

Practical examples

The following are some examples illustrating the daily use oflsof:

  • See which files have a specific process open:

    sudo lsof -p 1234

  • Find processes that are using a port:

    sudo lsof -i TCP:22

  • List all files opened by a user:

    sudo lsof -u juan

  • Detect processes that keep a deleted file open:

    sudo lsof | grep deleted

  • Get only PID from processes using a directory:

    sudo lsof -t +D /var/log

  • Use machine-readable output for a script:

    sudo lsof -F pct -i TCP:80

Security considerations

Becauselsofyou can reveal sensitive information (file routes, user names, network connection details), your execution usually requires root privileges to view the information of all processes. In environments where the principle of less privilege is applied, it is recommended to restrict access tolsofby sudo or by specific kernel capabilities.

Conclusion

The commandlsofis a powerful and versatile tool that belongs to the kit of any Linux administrator. Dominating your options allows you to quickly diagnose resource problems, audit file use and monitor system network activity. Practice with the examples shown and see the manual page (man lsof) will help you to make the most of this utility.

This work is under aCreative Commons License Attribution 4.0 International for Francesc Roig francesc @ vivaldi.net.

EnglishenEnglishEnglish