Sobes.tech
Junior

How to view the list of file descriptors in Linux?

sobes.tech AI

Answer from AI

The list of file descriptors can be viewed using the lsof command.

# Display all open files and descriptors for all processes
lsof

# Display open files and descriptors for a specific process by PID
# Replace <PID> with the process ID of interest
lsof -p <PID>

# Display open files and descriptors for all processes of a user
# Replace <username> with the username
lsof -u <username>

# Display open files and descriptors for a specific command
# Replace <command> with the command name
lsof -c <command>

# Display open files and descriptors related to network connections
lsof -i

# Display open files and descriptors related to a specific port
# Replace <port_number> with the port number
lsof -i :<port_number>

# Display open files and descriptors related to a specific file or directory
# Replace <file_or_directory> with the path to the file or directory
lsof <file_or_directory>

lsof outputs information in columns:

  • COMMAND: The name of the command associated with the process.
  • PID: Process ID.
  • USER: The user owning the process.
  • FD: File descriptor. Can be:
    • cwd: Current working directory.
    • rtd: Root directory.
    • txt: Text file (executable code).
    • mem: Memory map file.
    • mmap: Mapped file in memory.
    • <N>u: File descriptor <N> opened in "read/write" mode.
    • <N>r: File descriptor <N> opened in "read only" mode.
    • <N>w: File descriptor <N> opened in "write only" mode.
    • <N>l: File descriptor <N> is locked.
  • TYPE: Node type:
    • REG: Regular file.
    • DIR: Directory.
    • CHR: Character device.
    • BLK: Block device.
    • FIFO: Named pipe.
    • SOCK: Socket.
  • DEVICE: Device number.
  • SIZE/OFF: File size or offset.
  • NODE: Inode number.
  • NAME: File name.

You can also use the /proc filesystem. For each process (PID), /proc/<PID>/fd/ is a directory containing symbolic links to the files opened by that process. Each link is named after the file descriptor number.

# View file descriptors for a process with PID <PID>
# Replace <PID> with the process ID of interest
ls -l /proc/<PID>/fd/

The output of ls -l will show the descriptor number and the file it points to.