lsof (List Open Files)
The lsof command stands for List Open Files. Since "Everything is a file" in Linux (including network sockets, pipes, and devices), lsof is an incredibly powerful tool for diagnosing system issues, checking port usage, and monitoring process activity.
1. Basic Usage
lsof [options]
- Note: Because it accesses system-wide information, it is typically run with
sudo.
2. Key Options
| Option | Name | Description |
|---|---|---|
-u |
user | Lists files opened by a specific user. |
-p |
PID | Lists files opened by a specific Process ID. |
-i |
internet | Lists network connections (Internet addresses). |
-c |
command | Lists files for processes starting with a specific name. |
+D |
directory | Searches for processes using files within a specific directory. |
-t |
terse | Returns only the PID. Useful for piping into the kill command. |
3. Practical Examples
① Identifying which process is using a specific port
Essential for resolving "Address already in use" errors:
sudo lsof -i :80
② Finding who is using a specific file or directory
Find the culprit preventing you from unmounting a drive:
lsof +D /mnt/data
③ Listing all network connections for a specific user
lsof -u kimcomputer -i
④ Viewing all files opened by a command
lsof -c nginx
4. [Tip] Understanding FD and TYPE
Pay attention to these columns in the output:
* FD (File Descriptor): cwd (Current Working Directory), rtd (Root Directory), 0u (Standard Input), etc.
* TYPE: REG (Regular file), DIR (Directory), IPv4/IPv6 (Network sockets), unix (UNIX domain socket).