brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: lsof +D folder lists every process that has something open in it

Lsof
~/tips/tip-lsof-plus-d-directory-in-use

lsof +D /mnt/backup

Shows which processes keep files or the folder itself open anywhere under a directory.

A folder that will not unmount, or a disk that says it is busy, is annoying because the message never tells you who is holding it. I’d ask lsof about the whole folder instead of guessing.

lsof +D /mnt/backup

The manual says +D searches for all open instances of the directory and all the files and directories it contains, to its complete depth. Each row names the command, the PID and the user, plus the file descriptor and the path.

With a background sleep started from inside a folder called busy, lsof 4.95.0 printed this:

COMMAND PID USER   FD   TYPE DEVICE SIZE/OFF   NODE NAME
sleep   456 root  cwd    DIR  254,0     4096 704519 busy

The cwd in the FD column means the process has the folder as its current working directory. That is the most common culprit, usually a shell that someone left sitting in the folder. The fix is to cd out of it or stop that process.

For a script, -t prints just the process IDs without a header, as the manual puts it, so they are easy to use programmatically:

lsof -t +D /mnt/backup

If you only care about the top level, +d searches that one directory and the files in it, and it does not descend. It is faster for that reason.

One caveat: the manual warns that lsof may process +D slowly and need a large amount of memory for it. On a big tree, try +d first, or ask about one mount point instead of the whole disk. Neither option follows symbolic links inside the folder unless you add -x.

Further reading: lsof(8) manual

More Lsof tips sudo lsof -nP -iTCP -sTCP:LISTEN All Lsof tips (2) All topics

Link