Linux - find what is preventing you from unmounting a drive

Disclaimer: I've had this problem for probably four months, ever since I started running Plex Media Server on my headless linux machine at home, whilst storing all my actual media on a nice external portable drive. Usually I just yank it, but then I watch the drive letters run themselves up obscenely high before I need to reboot.
So you've gone through the process of mounting your drive in Linux:
> sudo fdisk -l
Device Boot = /dev/sdb1 (and a bunch of other technical information regarding drive size, id, and such)
>

> sudo mount -t ntfs-3g /dev/sdb1 /media/TOSHIBA
>

You run a bunch of stuff, get it all working, then find you need to take the drive to work the next day, so you try to unmount it.

 > sudo umount /media/TOSHIBA
umount: /media/TOSHIBA: device is busy.
(In some cases useful info about processes that use the device is found by lsof(8) or fuser(1))
>

Well, being a Windows guy at heart, and not really understanding why everything here needs to be so technical, this message never told me ANYTHING. I would try typing just plain "lsof" or "lsof(8)" or "fuser(1)" with no useful results.

Then I asked a friend.

"lsof | grep <stuff>," he said.

"Like, <stuff> would be the /dev/sdb1?"

"Yeah."

So I tried it:
> sudo lsof | grep /dev/sdb1
mount.ntf     2096      root     3u     BLK    8,33 0x1d1ba997e00       2897182   /dev/sdb1

"Oh," he said. "Try the mount path. /dev/sdb1 is the device which is mounted somewhere else."

> sudo lsof | grep /media/TOSHIBA
>

"Nothing," I said. "Just a blank line."

"Looks like no program has any file open on it?"

"Let me try again."

bash     2068     daniel    cwd    DIR    8,33     8192    17459  /media/TOSHIBA
grep     2254     root       cwd    DIR    8,33     8192     17459  /media/TOSHIBA
lsof     2255     root       cwd    DIR    8,33     8192     17459  /media/TOSHIBA

"Ahh...It may have been because I was still cd'd into it."

"Yes!"


So lessons learned:
  • grep, no matter how weird and complicated it looks with all those pipes and stuff, is still VERY useful. 
  • lsof is the command of choice for figuring this out. 
  • Use the mount point rather than the drive itself when searcing the lsof output text. 
  • Even just navigating into a drive will lock it from being unmounted - it's not like in Windows where if you "Safely Remove Hardware" or yank the USB cable, the computer conveniently closes the explorer window for you.

No comments:

Post a Comment

Comment loud, comment often. But comment on the content!

All comments are filtered through to my email, so your spam will never make it. Unless, of course, you wanted to try injection attacks into my email, which would probably not happen since Blogger just tells me that a comment is awaiting moderation and doesn't bother to tell me what it says. I trust Blogger like that..