Reference Linux
In this tutorial we will learn about lsof
command.
We run the lsof
command to list all the open files.
$ lsof
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
lsof 239 yusufshakeel cwd DIR 1,4 736 2 /
The FD column stands for file descriptor.
FD column can have the following values.
FD column can also have values like 1u
. Where u
implies read and write mode. There are other modes as well like r
for read and w
write.
Value for TYPE column can be the following.
To list all the files opened by a user we use lsof -u username
command where username is the name of the user.
To know your username run whoami
command.
In the following example we are listing all the files opened by user yusufshakeel.
$ lsof -u yusufshakeel
To list all the IPv4 network files that are open we run the following command.
$ lsof -i 4
To list all the IPv6 network files that are open we run the following command.
$ lsof -i 6
To list all the open files for a given PID we run the lsof -p PID
command.
In case the files are not getting listed properly then we can add sudo
to the command like sudo lsof -p PID
.
In the following example we are listing all the process with PID 1.
$ lsof -p 1
If we want to list all the open files from a set of PIDs then we run the lsof -p PID1,PID2,...
command where PID1, PID2 are the PID values.
In the following example we are listing all the open files with PID 1 and 2.
$ lsof -p 1,2
To list all the process running on a given port we use the following command lsof -i :PORT_NUMBER
.
In the following example we are listing all the processes running on port 80.
lsof -i :80
In the following example we are listing all the process running on port 443.
lsof -i :443
To list all the processes running on a set of port numbers we use the following command lsof -i :PORT1,PORT2,...
where PORT1, PORT2 are port numbers.
In the following example we are listing all the processes running on port 80 and 443.
$ lsof -i :80,443
To list all the TCP connections we run the following command.
$ lsof -i tcp
To list all the UDP connections we run the following command.
$ lsof -i udp
To kill all the processes belonging to a particular user we run the following command kill -9 $(lsof -t -u username)
.
In the following example we are killing all the processes belonging to user johndoe.
kill -9 $(lsof -t -u johndoe)
To kill all the processes running on a particular port we run the following command kill -9 $(lsof -t -i :PORT_NUMBER)
.
In the following example we are killing all the processes running on port 80.
$ kill -9 $(lsof -t -i :80)
Similarly, if we want to kill all the processes on port 443 then we will run the following command.
$ kill -9 $(lsof -t -i :443)
To kill all the processes running on a given set of port numbers we use the following command kill -9 $(lsof -t -i :PORT1,PORT2,...)
where PORT1, PORT2 are port numbers.
In the following example we are killing all the processes running on port 80 and 443.
$ kill -9 $(lsof -t -i :80,443)
ADVERTISEMENT