When managing a Linux server, you will inevitably encounter a situation where you try to unmount a USB drive and receive a “Device is busy” error, or you attempt to start a web server like Nginx only to be told that “Port 80 is already in use.” To solve these problems, you must identify exactly which background application is currently holding onto that file or locking that network port. In Linux, everything (including network connections and hardware devices) is treated mathematically as a “file.” Therefore, the ultimate diagnostic tool for these situations is lsof, which stands for “List Open Files.”
Basic Usage: Identifying What is Using a File or Directory
If you cannot delete a file or unmount a drive because the system claims it is busy, lsof will tell you precisely which program is the culprit.
- Open your Linux terminal. (Note: You usually need root/sudo privileges to see files owned by other users).
- Type the command followed by the absolute path to the locked file or directory:
sudo lsof /var/log/syslog - Press Enter.
The terminal will output a table. Pay close attention to the COMMAND column (which tells you the name of the program, e.g., rsyslogd) and the PID column (the Process ID). If you need to forcefully release the file, you can take that PID and kill it using the kill command (e.g., sudo kill -9 1234).
Finding What is Listening on a Specific Network Port
This is arguably the most common use case for system administrators. If an application refuses to start because its required network port is occupied, you use the -i (internet) flag to inspect network connections.
sudo lsof -i :80
This specific command searches the entire system for any application actively listening on port 80 (standard HTTP traffic). The output might reveal that an old, forgotten instance of Apache is still running in the background and hogging the port, preventing your new Nginx server from starting.
You can also check for specific protocols. To find out what application is using UDP port 53 (DNS):
sudo lsof -i udp:53
Listing All Files Opened by a Specific User
If you suspect a specific user account on your shared server is behaving maliciously or running a script that is consuming too many system resources, you can use the -u (user) flag to list every single file that user currently has open across the entire machine.
sudo lsof -u john_doe
Listing All Files Opened by a Specific Program
Conversely, if you know the name of the program but want to see every configuration file, log file, and network port it is currently touching, use the -c (command) flag.
sudo lsof -c mysql
This will dump an incredibly detailed list of every single file the MySQL database engine is actively interacting with, which is invaluable for debugging database corruption or locating hidden configuration files.