Sometimes a disk will not unmount, a port is already taken, or deleted data does not free space. You need to know which process has something open. lsof and fuser answer that. Either may need installing: lsof is usually its own package and fuser comes in psmisc.
lsof: list open files
$ lsof /var/log/app.log
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
app 2210 maria 3w REG 259,2 48211 1311021 /var/log/app.logFD shows the descriptor number and how it is open: r read, w write, u both. Entries such as cwd and txt mean the working directory and program file.
Run without arguments, lsof lists a huge amount, so narrow it:
lsof -p 2210 # files opened by one process
lsof -u maria # files opened by one user
lsof -i :22 # network use of port 22As an ordinary user you normally see only details of your own processes. Use sudo to see the rest.
Deleted but still open
Removing a file removes its name. The space is freed only when no process still has it open. This finds such files:
$ sudo lsof +L1
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NLINK NODE NAME
app 2210 root 3w REG 259,2 104857600 0 1311021 /var/log/old.log (deleted)+L1 selects open files with a link count below 1. Restarting the program, or having it reopen its logs, releases the space.
fuser: just the PIDs
$ fuser -v /var/log/app.log
USER PID ACCESS COMMAND
/var/log/app.log: maria 2210 F.... appFor a busy mount point, add -m to see every process using that filesystem:
sudo fuser -vm /mnt/usbFor a port, name the protocol:
sudo fuser -v 22/tcpfuser -k kills the processes it finds, with SIGKILL unless you choose another signal. Always run it without -k first. On a mount such as /, -km could take down the whole system.
Try it
Run sleep 300 > /tmp/demo.txt &, then lsof /tmp/demo.txt and fuser -v /tmp/demo.txt. End the job with kill %1. The processes and cron lab is a good place to experiment.
Check your understanding
Finding who is using a file: lsof and fuser
All 4 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.