lsof
lsof (List Open Files) is a command-line utility used to display a list of all open files and the processes that opened them. It is widely used for monitoring system resources and troubleshooting. Here's a basic tutorial on how to use lsof:
Basic Usage
To list all open files on your system, simply type:
lsof
This will display a list of all open files, including the command name, process ID (PID), user, file descriptor (FD), and file type.
Common lsof Options
-
List Open Files by a Specific Process:
To list the files opened by a particular process, use the
-pflag followed by the PID of the process:lsof -p <PID> -
List Open Files for a Specific User:
To list files opened by a particular user, use the
-uflag followed by the username:lsof -u <username> -
List Open Files for a Specific File:
You can use
lsofto check which process has a particular file open. For example, if you want to see which processes have a specific file open:lsof <filename> -
List Open Files on a Specific Device:
Use the
-dflag followed by the device file (e.g.,/dev/sda1) to list all files opened on that device:lsof -d <device> -
List Open Files for a Specific Port:
If you want to see which processes are listening on a specific port (e.g., port 80), use the
-ioption followed by the port number:lsof -i :80You can also use it for protocols:
lsof -i tcp:80 -
List All Network Connections:
To see all network connections and their status, use the
-iflag without a specific port:lsof -i -
List Open Files in a Directory:
To list all open files within a specific directory, use the
+Doption:lsof +D /path/to/directoryNote: This might take a while if the directory contains a large number of files.
-
List Files with Specific File Descriptor:
You can filter by the file descriptor (FD). For example:
lsof -d 4This will list files associated with file descriptor 4 (usually standard file descriptors 0, 1, and 2 are stdin, stdout, and stderr, respectively).
-
Show Process with Their Network Connections:
To show processes that are connected to the internet or local network, you can combine options like
-iand-s:lsof -i -sTCP:LISTENThis will show all processes listening on TCP ports.
Example Outputs
-
Listing all open files:
$ lsof COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME bash 1234 user cwd DIR 8,1 4096 1234 /home/user bash 1234 user txt REG 8,1 77840 5678 /bin/bash -
Listing files opened by a specific user:
$ lsof -u user COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME vim 5678 user cwd DIR 8,1 4096 1234 /home/user
Advanced Usage
-
Kill Processes Using a Specific File:
If a file is locked or causing issues, you can find the process using it withlsofand then kill it:lsof /path/to/file kill <PID> -
List Files Opened by a Specific Command:
For example, to list files opened by theapache2process:lsof -c apache2 -
Show Processes Using a Specific Port:
For example, to see which processes are using port 443 (HTTPS):lsof -i :443