Sobes.tech
Middle

How can you find out which files a program is currently working with in Linux?

sobes.tech AI

Answer from AI

Using the lsof utility (list open files).

# Basic usage of lsof to display a list of all open files
lsof

To get a list of open files by a specific process (by PID):

# Display open files for process with PID 1234
lsof -p 1234

To get a list of open files by a specific command (by name):

# Display open files for all processes named "nginx"
lsof -c nginx

To get a list of open files by a specific user:

# Display open files for user "user1"
lsof -u user1

Additional lsof flags:

Flag Description
-i List network connections (sockets)
-n Do not convert IP addresses to hostnames
-P Do not convert ports to service names
-r [N] Repeat lsof every N seconds

Example of usage to determine which process is using a specific file:

# Which process is using the file /var/log/syslog?
lsof /var/log/syslog

The output of lsof includes the following columns:

  • COMMAND: Name of the command that started the process.
  • PID: Process ID.
  • TID: Thread ID (if applicable).
  • USER: Name of the user who started the process.
  • FD: File descriptor.
  • TYPE: Node type (DIR, REG, FIFO, CHR, BLK, SOCK, etc.).
  • DEVICE: Device identifier.
  • SIZE/OFF: File size or offset.
  • NODE: Inode number.
  • NAME: File name or network address.