Many times, you may need to find out who is using a file in Linux. You may need this information to know which process or user has opened the file. This is common requirement when you try to delete a file and get the message saying it is in use, or it is open and cannot be deleted. You can easily find out this information using lsof command which searches kernel memory to find out the list of open files. They can be either directories, regular file, network file or even a stream.
How to Find Out Who is Using File in Linux
Lsof command allows you to view open files in various ways. We will look at 3 common ways to use lsof command.
View Open Files in Linux
You can use the following lsof command to view open files in Linux
$ lsof /dev/null COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1327 ubuntu 0r CHR 1,3 0t0 6 /dev/null nginx 31826 ubuntu 0u CHR 1,3 0t0 6 /dev/null nginx 31826 ubuntu 1u CHR 1,3 0t0 6 /dev/null
If you want to view open files for specific user, use the lsof command with -u option followed by username whose open files you want to view.
$ lsof -u ubuntu COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1327 ubuntu cwd DIR 202,1 4096 2 / systemd 1327 ubuntu rtd DIR 202,1 4096 2 / systemd 1327 ubuntu txt REG 202,1 1616248 71872 /lib/systemd/systemd systemd 1327 ubuntu mem REG 202,1 1700792 26011 /lib/x86_64-linux-gnu/libm-2.27.so systemd 1327 ubuntu mem REG 202,1 121016 58475 /lib/x86_64-linux-gnu/libudev.so.1.6.9 ...
Similarly, if you want to view who or which user is using a specific port use -i option, as shown below. Here is the command to view processes running on port 80.
lsof -i TCP:80 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 31826 ubuntu 8u IPv4 873070 0t0 TCP *:http (LISTEN)
In this article, we have learnt 3 ways to view open files in Linux, using lsof command. You can view open files by all users, open files by specific user and processes using a specific port.