Have you ever tried to close your shell or unmount a drive only to get an error that one or more files are in use? Or perhaps you’ve tried to edit a file only to find it’s locked by another program?
Maybe you’re worried that someone has somehow gained unauthorized access to your Linux system. Using a tool called lsof, you can see which files are open, even over network connections.
What Is lsof?
lsof is a utility that lists open files. Victor Abell originally developed it at Purdue University. It’s available for several Unix implementations, including Linux. It’s currently maintained by the lsof-org team on GitHub.
Installing lsof on Linux
There’s a good chance that you already have lsof installed on your system. Try typing lsof at the command line. If it isn’t, you can install it through your distro’s package manager.
On an Ubuntu or Debian system, type:
sudo apt install lsof
sudo pacman -S lsof
And on RHEL, Rocky Linux, and Oracle Linux:
sudo dnf install lsof
Viewing Open Files on Linux With lsof
Using lsof is straightforward. You can just invoke it at the command line to see any open files belonging to you:
lsof may list processes belonging to root as “Permission denied.” To see all files open by all processes system-wide, run it as root:
lsof will show the command, the PID, the user who invoked it, the file descriptor, the type, the device, the size, the node, and the absolute pathname of the open file.
If you try to unmount a drive such as an optical drive and get an error that files are in use, you can see which process is using the file and then exit or kill it.
To see any internet sockets currently in use on your system, use the -i option:
sudo lsof -i
You could detect possible intrusion if you notice something suspicious on your system, but more sophisticated attackers may be able to cover their tracks better.
The -r option puts lsof into repeat mode, where it will display results after a certain interval until you press Ctrl + C. By default, it runs every 15 seconds, but you can change it. For example, you can run the command every 10 seconds by typing:
lsof -r 10
As with other Linux utilities, you can combine these switches. Suppose you wanted to watch your internet connection every five seconds. You can do that with lsof by typing:
lsof -i -r 5
Now You Can Track Which Linux Processes Have Open Files
With lsof, you can track down which processes have open files and fix any problems they might cause.
Open files are just one facet of Linux processes. There are so many ways to manage processes on Linux. It’s easy to start, stop, and examine processes in Linux so you can get the most out of your system.