Site icon LinuxCommands.site

lsof command tutorial in linux/unix with examples and use cases

linux lsof command – list open files

In the Linux system, everything is a file. Files can access not only regular data, but also network connections and hardware. Therefore, the lsof command can not only view the files and directories opened by the process, but also view the socket information such as the port that the process listens to.

This article will introduce the basic usage of the lsof command. The demo environment of this article is ubuntu 19.04.

Syntax

lsof [option]

Common options

Output

Here are some common types in FD column and TYPE column.

Common types in the FD column are cwd, rtd, txt, mem, some numbers, and so on.

The common REG and DIR in the TYPE column represent ordinary files and directories, respectively.

Exmaples

View which processes have the specified file opened

In the following example, we will use the lsof command to see which processes are opening the specified file, such as querying the process that opens the /bin/zsh file:

➜  ~ lsof /bin/zsh
COMMAND  PID     USER  FD   TYPE DEVICE SIZE/OFF   NODE NAME
zsh     1964 ylspirit txt    REG    8,1   848960 135362 /usr/bin/zsh
zsh     2129 ylspirit txt    REG    8,1   848960 135362 /usr/bin/zsh
➜  ~

See which processes have opened a certain directory and the files in the directory

The +d option does not perform recursive queries, only find processes that have opened the specified directory and files and directories under the specified directory, such as

➜  ~ sudo lsof +d /var/log

The +D option will recurse the specified directory:

➜  ~ sudo lsof +D /var/log

View opened network-related files

The -i option is used to view the opened network-related files.

lsof -i [46][protocol][@hostname|hostaddr][:service|port]

The -i option will output both IPv4 and IPv6 opened files by default:

➜  ~ sudo lsof -i

Only list files opened by IPv4

➜  ~ sudo lsof -i 4

List files related to port 22

➜  ~ sudo lsof -i:22

View all files opened by a user

The -u option can specify a user name or user ID, and like the -c option, multiple user names or user IDs can be separated by commas, or the condition can be reversed by the symbol ^.

View network-related files opened by user ylspirit

➜  ~ sudo lsof -i -a -u ylspirit

Exclude a user

➜  ~ sudo lsof -i -a -u ^ylspirit

View the file opened by the program with the specified name

The -c option can match the name of the program (executable file) that the process runs. For example, we want to find a list of files opened by programs beginning with the letter sy:

➜  ~ sudo lsof -c sy

Reference:

lsof man page

Exit mobile version