lsof (acronym for “list opened files”), is command that show list of opened files and the program that open then.
This is useful, because program can lock your files and you wont be able to delete them or change them. So by using this command you can see what is locking your files, stop it and then delete the files, or do what ever you want to them.
it is better to use it with root privilege, otherwise it wont be able to show you the all the processes that open the files.
the lsof command show the following columns with the following order:
COMMAND PID TID USER FD TYPE DEVICE SIZE/OFF NODE NAME
List of the columns and there meaning:
- COMMAND – contain the first characters of the command associate with the process that is opening the file. By default show only the first 9 characters. If we want to print all the command charterers’ info that it get from the kernel, we can use +c 0
- PID – the process Id of the process that open the file.
- TID – the task (thread) identification of the task that is opening the file.If this columns is empty then it mean it isn’t task but a process.
- USER – the user name (or user id) that to whom the process that opening the file belong.
- FD – can be the file descriptor number of the opened file. (the file desciptor number for the process that openening the file).
- TYPE – the type of the node associate with the file, REG is used for regular file.
- DEVICE – contain the device type.
- SIZE/OFF – the size of the file.
- NODE – the node number, in case the file is a local file.
- NAME – the name of the file prefix with the full path to it
In the example below we will open file with vim, and then ask for the opened file wit the same name, vim will open file with the same name prefix with swp
In one terminal we open the file with vim.
oren@oren-computer:~/c-programming $ vim arguments.c
In the other terminal, we use lsof to see what is open the file
oren@oren-computer:~/c-programming $ sudo lsof | grep arguments vim 8146 oren 4u REG 8,8 12288 1455114 /home/oren/c-programming/.arguments.c.swp
Since in Linux everything is a file, we can use lsof not only for regular file on the hard drive, but also to inspect and debug connection and network problems.
if we want to check what is open a specific file we run:
and it will know the process id of the process that is opening the file, and the command that was used to run this process.