Linux lsof command

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:

  1. 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
  2. PID – the process Id of the process that open the file.
  3. 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.
  4. USER – the user name (or user id)  that to whom the process that opening the file belong.
  5. FD – can be the file descriptor number of the opened file. (the file desciptor number for the process that openening the file).
  6. TYPE – the type of the node associate with the file, REG is used for regular file.
  7. DEVICE – contain the device type.
  8. SIZE/OFF – the size of the file.
  9. NODE – the node number, in case the file is a local file.
  10. 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.

$ vim arguments.c

In the other terminal, we use lsof to see what is open the file

$ 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:
lsof <full-path/file-name>
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.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s