The lsof
(List Open Files) is an essential tool for Linux system administrators, providing critical insights into file usage across the system. As almost everything in Linux is treated as a file — be it regular files, directories, or network sockets — lsof
can help you troubleshoot and optimize system performance.
Basic Usage
To get a comprehensive list of all open files, run:
sudo lsof
Running this command may produce a large output. Thus, it’s practical to filter the results to suit specific needs.
Use Cases
a) Files by an User
To check which files are opened by a specific user, utilize:
sudo lsof -u <username>
This command will return details like process ID (PID), file descriptor, type of file, and file path.
b) Files by a Process
To see which files a particular process has opened, use:
lsof -p <PID>
This is particularly useful for debugging issues related to specific applications.
c) Network Connections
lsof
can also be used to monitor network activity.
To display all open network connections:
sudo lsof -i
To filter by protocol, use:
sudo lsof -i tcp # For TCP connections
sudo lsof -i udp # For UDP connections
To check connections on a specific port, use:
sudo lsof -i :<port_number>
d) Deleted Files
Sometimes, files may be deleted while still being used by a process. To list such files, use:
sudo lsof | grep deleted
This can be crucial for identifying resource leaks or for freeing up disk space.
Whether troubleshooting, optimizing performance, or investigating unexpected behavior, mastering lsof
is essential for any Linux administrator.