Skip to content

Linux Foundations / Manage a Linux host ยท Step 34 of 50

Lesson: Finding who is using a file: lsof and fuserSwitch
โ† Linux Foundations

System administration

Finding who is using a file: lsof and fuser

Use lsof and fuser to find which processes hold files, directories and ports.

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

bash
$ 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.log

FD 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:

bash
lsof -p 2210        # files opened by one process
lsof -u maria       # files opened by one user
lsof -i :22         # network use of port 22

As 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:

bash
$ 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

bash
$ fuser -v /var/log/app.log
                     USER        PID ACCESS COMMAND
/var/log/app.log:    maria      2210 F.... app

For a busy mount point, add -m to see every process using that filesystem:

bash
sudo fuser -vm /mnt/usb

For a port, name the protocol:

bash
sudo fuser -v 22/tcp

fuser -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.