Getting the list of open files

We know that there can be millions of files available in a system, which can be binary files, text files, directories, and so on. When a file is not in use, they are just available on a storage device as 0 and 1. To view or process a file, it needs to be opened. An application that is executing may open multiple files. Knowing what files are opened by a running application is very useful. To know the list of opened files, the lsof command is used.

Executing the following command gives the list of all opened files:

$ lsof

This gives a huge output of all the opened files.

Knowing the files opened by a specific application

To know the list of files opened by a specific application, first get the Process ID (PID) of the running application:

$ pidof application_name

For example, let's run cat without any parameter:

$ cat

In another terminal, run the following commands:

$ pidof cat
15913
$ lsof -p 15913

Alternatively, we can directly write the following command:

$ lsof -p 'pidof cat'

The following is a sample screenshot of the lsof output:

Knowing the files opened by a specific application

In the output, we see that there are various columns of results. The first column is COMMAND—that is, for the application this file has been opened, the PID column specifies the PID with which the file has been opened, USER tells which user has opened the file, FD is the file descriptor, TYPE specifies the type of file, DEVICE specifies the device number with values separated by a comma, SIZE/OFF specifies the size of the file or the file offset in bytes, and NAME is the filename with the absolute path.

In the output, we can see that the application has opened cat binary from /usr/bin. It has also loaded the shared library files such as libc-2.21.so and ld-2.21.so available in /usr/lib64/. Also, there is a character device dev/pts/2 that has been opened.

Listing the applications that opened a file

We can also find out which all applications opened a file. This can be done by executing the following command:

$ lsof /usr/bin/bash

The following is the sample output:

Listing the applications that opened a file

From the output, we can see that the bash file has been opened by six running applications.

Knowing the files opened by a user

To know the list of files opened by a specific user, run lsof with the -u option. The syntax is as follows:

lsof -u user_name

For example, consider the following command:

$ lsof -u foo | wc -l
525

This means, currently 525 files are opened by the user root.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.75.27