lsof — check open files and ports
💬 "lsof command"
lsof shows open files and sockets. It resolves port conflicts and the 'deleted but disk space not reclaimed' issue.
In particular, +L1 finds files that have been deleted but are still held by a process.
- Concept: Lists files, sockets, and devices opened by processes.
- File name: The path used by that process.
- (deleted): A file that has been deleted but is still open.
- FD: File descriptor type (cwd, txt, numeric).
Common options
| Option | Description |
|---|---|
| -p <PID> | Files opened by a specific process |
| -i :<port> | Processes using a specific port |
| +L1 | Find files with a link count below 1 (deleted files) |
| -u <user> | Files for a specific user |
3 essential command combinations
lsof -i :443— Check processes using port 443lsof +L1 | head— Check deleted but still-held fileslsof -p 2210 | head— Check files opened by a process
💬 "Is there a way to save time with this command?"
These are common situations on production servers, organized in order.
Step 1 · Check port usage
See which process is holding the port.
lsof -i :443
Step 2 · Check deleted files
Check this when disk space isn’t being freed.
lsof +L1 | sort -k7 -n | tail
Step 3 · Restart or rotate
Restart the process or rotate the logs to reclaim space.
systemctl restart myapp
How it is used in practice
1. Deleted but disk usage unchanged
Situation — You removed logs with rm, but df usage hasn’t changed.
lsof +L1 | grep -i log
Result — Find the deleted file and PID held by the process.
Point — Restarting the process reclaims the space. For a root fix, use logrotate.
2. Process occupying a port
Situation — You need to find who is using port 8080.
lsof -i :8080
Result — You get the PID and process name, so you can pinpoint what to clean up.
Point — You can see the same information with ss -lntp.
Caution
- Running plain lsof produces a huge output. Use filters (-i, -p, +L1).
- Viewing other users’ file information requires privileges, so sudo may be needed.
- Restarting a process that holds deleted files can cause a brief service interruption.
Actual execution screen
This is the result of checking deleted but held log files and the process occupying port 443.
!lsof command output: deleted files and port occupancy
An actual production server
Source (HTML): https://games.aidebatehub.com/programs/linux/troubleshooting/lsof.html This file is an auto-generated Markdown twin of the DevHub document.
AI Knowledge Hub
Visitor Comments