471

I've got some samba drives that are being accessed by multiple users daily. I already have code to recognize shared drives (from a SQL table) and mount them in a special directory where all users can access them.

I want to know, if I remove a drive from my SQL table (effectively taking it offline) how, or even is, there a way to unmount a busy device? So far I've found that any form of umount does not work.

Ignoring the possibility of destroying data - is it possible to unmount a device that is currently being read?

Javier Arias
  • 2,329
  • 3
  • 15
  • 26
Max
  • 5,799
  • 3
  • 20
  • 27
  • 5
    A more general answer addressing more causes for failing umount is found here http://oletange.blogspot.dk/2012/04/umount-device-is-busy-why.html – Ole Tange Jun 22 '14 at 11:13
  • 9
    Hello, probably you `cd` to mounted dir, then you became root or login again then the other shell is trapped. Do `exit` on all shells. – Smeterlink May 05 '20 at 23:24
  • See: https://unix.stackexchange.com/questions/107885 – Karl Knechtel Feb 13 '23 at 20:28

16 Answers16

770

YES!! There is a way to detach a busy device immediately - even if it is busy and cannot be unmounted forcefully. You may cleanup all later:

umount -l /PATH/OF/BUSY-DEVICE
umount -f /PATH/OF/BUSY-NFS (NETWORK-FILE-SYSTEM)

NOTE/CAUTION

  1. These commands can disrupt a running process, cause data loss OR corrupt open files. Programs accessing target DEVICE/NFS files may throw errors OR could not work properly after force unmount.
  2. Do not execute above umount commands when inside mounted path (Folder/Drive/Device) itself. First, you may use pwd command to validate your current directory path (which should not be the mounted path), then use cd command to get out of the mounted path - to unmount it later using above commands.
Amit Verma
  • 8,660
  • 8
  • 35
  • 40
  • 41
    Note: `-l` here is a lowercase `L` (for "lazy unmounting"). ( See [this related answer](http://stackoverflow.com/a/96288/558008). ) – ジョージ Feb 21 '14 at 07:47
  • 4
    Worked. One nuance, if you are logged in through FTP client, you have to logout in order to successfully unmount folder. – Alexander Kim Oct 22 '14 at 16:47
  • They don't work. They both just hang for ever. (Debian 8, cifs-utils 2:6.4-1) – Hubro Sep 28 '16 at 08:44
  • 2
    `-l` / `--lazy` won't corrupt open files, but on Linux it seems [you can't know when the device is actually unmounted and can be removed](https://github.com/karelzak/util-linux/issues/493) – Tom Hale Aug 12 '17 at 06:14
  • 3
    Kinda scary. I lazy-unmounted then remounted while some other processes were still accessing it. So I guess I mounted it twice in the end to the same location? Not sure what that did. – sudo Sep 08 '17 at 00:42
  • 1
    Thanks, this answer help me with woeusb to create a bootable pendrive with windows – Lucas Prestes Oct 30 '18 at 23:57
  • 1
    Hi, it's very likely some process has some file descriptor open on your mount partition, follow the thread you have to use 'lsof' command to diagnostic and see if some process has an open file. In the case of the data base you should kill the processes or close the database before umount the partition. Use -L or -F can hide the real problem about the umount is failing and is not advisable. – Javier Gutiérrez-Maturana Sánc Jun 16 '20 at 11:02
  • 1
    Always worth checking of your current directory is on that drive. `cd` out of it if you are. – Greg Robson Jun 21 '20 at 18:59
  • -100 to me for trying to unmount my `pwd`, thanks @GregRobson. :facepalm: – Tyler R. Dec 09 '20 at 19:22
  • 1
    Starting a `tmux` session from a mounted directory that you later try to `umount` in one of your `tmux` windows/tabs will definitely confound. `lsof` and `grep` were very useful. – jmcarter9t May 14 '21 at 21:25
  • /PATH/OF/BUSY-DEVICE is what exactly? – shashank arora Dec 03 '21 at 19:32
  • @shashankarora - It represent the path of the busy device (e.g. drive), which you want to force unmount. – Amit Verma Dec 04 '21 at 17:36
  • umount -l /mnt/test – CS QGB Aug 30 '22 at 09:00
  • downvote for proposing dangerous lazy/forced unmount instead of closing opened files and preventing future access to the path you try to unmount. – thomas Oct 06 '22 at 19:18
  • @thomas - There must be a purpose why umount command comes with this option!! You should follow the entire manual because there's a caution-section in the answer w.r.t. the context set in the question. – Amit Verma Oct 08 '22 at 07:51
  • @AmitVerma - Have you ever manage to destroy a partition by mounting it twice? I already had this pleasure. Have a look at `tom-hale`'s answer if you really don't know why your answer is bad. IMHO your anwser is not w.r.t. the context of the question. Even with Samba you can id and kill processes blocking unmount without disturbing other users. – thomas Oct 12 '22 at 08:23
234

If possible, let us locate/identify the busy process, kill that process and then unmount the samba share/ drive to minimize damage:

  • lsof | grep '<mountpoint of /dev/sda1>' (or whatever the mounted device is)

  • pkill target_process (kills busy proc. by name | kill PID | killall target_process)

  • umount /dev/sda1 (or whatever the mounted device is)

Inspired_Blue
  • 2,308
  • 3
  • 15
  • 21
Frank Tudor
  • 4,226
  • 2
  • 23
  • 43
  • 14
    That doesn't return anything. I'm assuming its because its a network drive and I can't see the processes of other computers accessing the drive. Same deal with the "fuser" commands. – Max Oct 24 '11 at 16:40
  • oh hell... you need the samba commands... /usr/bin/smbclient service : See if this gets you started...http://tldp.org/HOWTO/SMB-HOWTO-8.html – Frank Tudor Oct 24 '11 at 17:17
  • 2
    The smb commands have actually been deprecated and replaced by "umount.cifs" .... which also doesn't work. It appears that I'm stuck with not being able to umount while its busy. – Max Oct 24 '11 at 18:00
  • 1
    If you are using Asuswrt-Merlin, you need to install `lsof`: `# opkg install lsof` – Tonatio Jul 24 '19 at 17:18
  • 7
    you need to sudo lsof to get some results – aheigins Apr 25 '20 at 10:14
  • One reason why the target device might be busy but not show up in `lsof` is if you have a `zfs` pool on it. In that case, `zpool export thepool` is the solution – lucidbrot May 23 '20 at 16:23
  • Technically, this answer did not answer the OP's question "Ignoring the possibility of destroying data - is it possible to unmount a device that is currently being read?". But I LOVE LOVE LOVE this answer! Being able to find the busy process and deal with it upfront, feels much more correct, than forcing umount. Upvoted! – RayLuo Oct 31 '20 at 21:35
  • A shorter version would be `lsof [mountpoint]`. And don't forget to run as a root or `sudo` – Slavik Meltser Aug 30 '22 at 05:47
  • `lsof +D ` or just `lsof ` also works. No need to grep! – Marco Nov 21 '22 at 10:11
156

Make sure that you aren't still in the mounted device when you are trying to umount.

Luci
  • 1,569
  • 1
  • 8
  • 2
  • 24
    Exactly, simply having current folder (located on target device) opened in your terminal (through e.g. cd command) is enaugh to stop the unmnounting process :) – jave.web Jan 28 '18 at 14:13
  • 3
    Yep, I had a shell running in a directory on the device. Closed the terminal window and voila – shender Dec 31 '18 at 20:31
  • 1
    Also, make sure there are not any other mount points inside the one you are trying to `umount`. – victe Jul 19 '19 at 08:19
  • @victe Thanks; I was mouting a folder using pfexec mount -F vboxfs carpetacompartida ~/Documents on Solaris 11; but Documents had subfolders and it was the issue. – Dani Aya Jan 29 '20 at 20:44
  • I noticed that the regular FAT32 doesn't care but ExFAT (like SSD drives) does care of PWD. – juzzlin Jun 17 '21 at 06:23
  • This is the best answer that actually answer the root cause. In most cases anyway. – lallolu Oct 14 '21 at 09:53
  • I forgot my normal user was cd'ed into the mounted device and had sudo'ed to root. I had to logout of root and cd out of the device before I could unmount it. – pacoverflow Dec 04 '22 at 02:18
101

Avoid umount -l

At the time of writing, the top-voted answer recommends using umount -l.

umount -l is dangerous or at best unsafe. In summary:

  • It doesn't actually unmount the device, it just removes the filesystem from the namespace. Writes to open files can continue.
  • It can cause btrfs filesystem corruption

Work around / alternative

The useful behaviour of umount -l is hiding the filesystem from access by absolute pathnames, thereby minimising further moutpoint usage.

This same behaviour can be achieved by mounting an empty directory with permissions 000 over the directory to be unmounted.

Then any new accesses to filenames in the below the mountpoint will hit the newly overlaid directory with zero permissions - new blockers to the unmount are thereby prevented.

First try to remount,ro

The major unmount achievement to be unlocked is the read-only remount. When you gain the remount,ro badge, you know that:

  1. All pending data has been written to disk
  2. All future write attempts will fail
  3. The data is in a consistent state, should you need to physcially disconnect the device.

mount -o remount,ro /dev/device is guaranteed to fail if there are files open for writing, so try that straight up. You may be feeling lucky, punk!

If you are unlucky, focus only on processes with files open for writing:

lsof +f -- /dev/<devicename> | awk 'NR==1 || $4~/[0-9]+[uw -]/'

You should then be able to remount the device read-only and ensure a consistent state.

If you can't remount read-only at this point, investigate some of the other possible causes listed here.

Read-only re-mount achievement unlocked ☑

Congratulations, your data on the mountpoint is now consistent and protected from future writing.

Why fuser is inferior to lsof

Why not use use fuser earlier? Well, you could have, but fuser operates upon a directory, not a device, so if you wanted to remove the mountpoint from the file name space and still use fuser, you'd need to:

  1. Temporarily duplicate the mountpoint with mount -o bind /media/hdd /mnt to another location
  2. Hide the original mount point and block the namespace:

Here's how:

null_dir=$(sudo mktemp --directory --tmpdir empty.XXXXX")
sudo chmod 000 "$null_dir"

# A request to remount,ro will fail on a `-o bind,ro` duplicate if there are
# still files open for writing on the original as each mounted instance is
# checked.  https://unix.stackexchange.com/a/386570/143394
# So, avoid remount, and bind mount instead:
sudo mount -o bind,ro "$original" "$original_duplicate"

# Don't propagate/mirror the empty directory just about hide the original
sudo mount --make-private "$original_duplicate"

# Hide the original mountpoint
sudo mount -o bind,ro "$null_dir" "$original"

You'd then have:

  1. The original namespace hidden (no more files could be opened, the problem can't get worse)
  2. A duplicate bind mounted directory (as opposed to a device) on which to run fuser.

This is more convoluted[1], but allows you to use:

fuser -vmMkiw <mountpoint>

which will interactively ask to kill the processes with files open for writing. Of course, you could do this without hiding the mount point at all, but the above mimicks umount -l, without any of the dangers.

The -w switch restricts to writing processes, and the -i is interactive, so after a read-only remount, if you're it a hurry you could then use:

fuser -vmMk <mountpoint>

to kill all remaining processes with files open under the mountpoint.

Hopefully at this point, you can unmount the device. (You'll need to run umount on the mountpoint twice if you've bind mounted a mode 000 directory on top.)

Or use:

fuser -vmMki <mountpoint>

to interactively kill the remaining read-only processes blocking the unmount.

Dammit, I still get target is busy!

Open files aren't the only unmount blocker. See here and here for other causes and their remedies.

Even if you've got some lurking gremlin which is preventing you from fully unmounting the device, you have at least got your filesystem in a consistent state.

You can then use lsof +f -- /dev/device to list all processes with open files on the device containing the filesystem, and then kill them.


[1] It is less convoluted to use mount --move, but that requires mount --make-private /parent-mount-point which has implications. Basically, if the mountpoint is mounted under the / filesystem, you'd want to avoid this.

Tom Hale
  • 40,825
  • 36
  • 187
  • 242
  • 5
    If `--lazy` is so dangerous, why is there not so much as a warning in the `umount` man page? All it says is "*Lazy unmount. Detach the filesystem from the file hierarchy now, and clean up all references to this filesystem as soon as it is not busy anymore.*" – bitinerant Jan 23 '20 at 14:26
  • 2
    Remounting as read-only and then retrying the unmount helped. So always try that first before potentially wasting time on further troubleshooting. – xdevs23 May 05 '21 at 22:12
  • @xdevs23: `mount -o remount,ro` + `umount` works if you have lots of sporadic writes but nothing actually hanging on the mount. Of couse, all processes trying to create writable files will get errors from read-only forward. – Mikko Rantalainen Jul 07 '21 at 14:57
  • `lsof +f -- /dev/device` helped me find the culprit process, and then I was able to unmount and remount – KayO Jan 21 '22 at 11:20
  • best answer, thanks. @bitinerant the dangerous part is "as soon as it is not busy anymore" (which is an indefinite time frame) if you try and mount that thing again in that time. already one commenter on the accepted answer seems to have done that. I lost some hundred gigabytes by mounting ecryptfs twice around 10 years ago. – thomas Oct 06 '22 at 19:20
51

Try the following, but before running it note that the -k flag will kill any running processes keeping the device busy.

The -i flag makes fuser ask before killing.

fuser -kim /address  # kill any processes accessing file
unmount /address
Arel
  • 1,339
  • 17
  • 22
user3751769
  • 619
  • 5
  • 3
  • 6
    `lsof | grep '/dev/` didn't return anything, but this works great! May want to also suggest `fuser -m /dev/` in case you want to find out the process before killing it. – modulitos Feb 10 '16 at 08:26
  • 3
    Running the fuser command immediately disconnected me from the VPS. – giorgio79 May 30 '16 at 13:06
  • There's no fuser in ubuntu 18.04 – Freedo Oct 02 '20 at 22:22
  • @giorgio79 If the current working directory of your shell is inside the device that you're trying to `umount`, of course, killing the shell is required to unmount the device. It's always best to do `cd /` before trying to umount anything. – Mikko Rantalainen Jul 07 '21 at 14:59
13

Before unmounted the filesysem. we need to check is any process holding or using the filesystem. That's why it show device is busy or filesystem is in use. run below command to find out the processes using by a filesystem:

fuser -cu /local/mnt/

It will show how many processes holding/using the filesystem.

local/mnt: 1725e(root) 5645c(shasankarora)

ps -ef | grep 1725 <--> ps -ef | grep <pid>

kill -9 pid

Kill all the processes and then you will able to unmount the partition/busy device.

shashank arora
  • 1,176
  • 11
  • 14
9

Check for exported NFS file systems with exportfs -v. If found, remove with exportfs -d share:/directory. These don't show up in the fuser/lsof listing, and can prevent umount from succeeding.

numberer6
  • 131
  • 1
  • 1
8

Just in case someone has the same pb. :

I couldn't unmount the mount point (here /mnt) of a chroot jail.

Here are the commands I typed to investigate :

$ umount /mnt
umount: /mnt: target is busy.
$ df -h | grep /mnt
/dev/mapper/VGTout-rootFS  4.8G  976M  3.6G  22% /mnt
$ fuser -vm /mnt/
                     USER        PID ACCESS COMMAND
/mnt:                root     kernel mount /mnt
$ lsof +f -- /dev/mapper/VGTout-rootFS
$

As you can notice, even lsof returns nothing.

Then I had the idea to type this :

$ df -ah | grep /mnt
/dev/mapper/VGTout-rootFS  4.8G  976M  3.6G  22% /mnt
dev                        2.9G     0  2.9G   0% /mnt/dev
$ umount /mnt/dev
$ umount /mnt
$ df -ah | grep /mnt
$

Here it was a /mnt/dev bind to /dev that I had created to be able to repair my system inside from the chroot jail.

After umounting it, my pb. is now solved.

SebMa
  • 4,037
  • 29
  • 39
7

Check out umount2:

Linux 2.1.116 added the umount2() system call, which, like umount(), unmounts a target, but allows additional flags controlling the behaviour of the operation:

MNT_FORCE (since Linux 2.1.116) Force unmount even if busy. (Only for NFS mounts.)
MNT_DETACH (since Linux 2.4.11) Perform a lazy unmount: make the mount point unavailable for new accesses, and actually perform the unmount when the mount point ceases to be busy.
MNT_EXPIRE (since Linux 2.6.8) Mark the mount point as expired. If a mount point is not currently in use, then an initial call to umount2() with this flag fails with the error EAGAIN, but marks the mount point as expired. The mount point remains expired as long as it isn't accessed by any process. A second umount2() call specifying MNT_EXPIRE unmounts an expired mount point. This flag cannot be specified with either MNT_FORCE or MNT_DETACH.

remram
  • 4,805
  • 1
  • 29
  • 42
chown
  • 51,908
  • 16
  • 134
  • 170
  • Unforunately these aren't NFS mounts, but CIFS. I will try the MNT_DETACH though. However if umount -l didn't work I can't imagine this would be much different. Thanks though! – Max Oct 24 '11 at 16:35
6

I recently had a similar need to unmount in order to change it's label with gparted.

/dev/sda1 was being mounted via /etc/fstab as /media/myusername. When attempts to unmount failed, I researched the error. I had forgotten to unmount a dual partitioned thumb drive with a mountpoint on /dev/hda1 first.

I gave 'lsof' a go as recommended.

$ sudo lsof | grep /dev/sda1

The output of which was:

lsof: WARNING: can't stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
Output information may be incomplete.
lsof: WARNING: can't stat() fuse file system /run/user/1000/doc
Output information may be incomplete.

Since lsof burped up two fuse warnings, I poked around in /run/user/1000/*, and took a guess that it could be open files or mount points (or both) interfering with things.

Since the mount points live in /media/, I tried again with:

$ sudo lsof | grep /media

The same two warnings, but this time it returned additional info:

bash 4350 myusername cwd DIR 8,21 4096 1048577 /media
sudo 36302 root cwd DIR 8,21 4096 1048577 /media
grep 36303 myusername cwd DIR 8,21 4096 1048577 /media
lsof 36304 root cwd DIR 8,21 4096 1048577 /media
lsof 36305 root cwd DIR 8,21 4096 1048577 /media

Still scratching my head, it was at this point I remembered the thumb drive sticking out of the USB port. Maybe the scratching helped.

So I unmounted the thumb drive partitions (unmounting one automatically unmounted the other) and safefly unplugged the thumb drive. After doing so, I was able to unmount /dev/sda1 (having nothing mounted on it anymore), relabel it with gparted, remount both the drive and thumb drive with no issues whatsoever.
Bacon saved.

endorpheus
  • 111
  • 1
  • 5
5
sudo fusermount -u -z <mounted path>

NB: do not use completition for the path as this will also freeze the terminal.

Mario Viti
  • 496
  • 1
  • 5
  • 10
4

Someone has mentioned that if you are using terminal and your current directory is inside the path which you want to unmount, you will get the error.
As a complementary, in this case, your lsof | grep path-to-be-unmounted must have below output:

bash ... path-to-be-unmounted
Eugene
  • 10,627
  • 5
  • 49
  • 67
2

Another alternative when anything works is editing /etc/fstab, adding noauto flag and rebooting the machine. The device won't be mounted, and when you're finished doing whatever, remove flag and reboot again.

jesjimher
  • 1,175
  • 1
  • 12
  • 17
2

Niche Answer:

If you have a zfs pool on that device, at least when it's a file-based pool, lsof will not show the usage. But you can simply run

sudo zpool export mypool

and then unmount.

lucidbrot
  • 5,378
  • 3
  • 39
  • 68
1

Multiple mounts inside a folder

An additional reason could be a secondary mount inside your primary mount folder, e.g. after you worked on an SD card for an embedded device:

# mount /dev/sdb2 /mnt       # root partition which contains /boot
# mount /dev/sdb1 /mnt/boot  # boot partition

Unmounting /mnt will fail:

# umount /mnt
umount: /mnt: target is busy.

First we have to unmount the boot folder and then the root:

# umount /mnt/boot
# umount /mnt
gökçe
  • 23
  • 5
0

In my case, I couldn't unmount a partition that was mounted to a directory that was an AFP share. (sharing into an Apple bonjour/avahi mdns world) I moved all the logins on the server to their home directory; I moved all the remotely connected Macs to some other directory. I still couldn't unmount the partition even with umount -f So I restarted the netatalk daemon on the server.
(/etc/netatalk/afp.conf has in it the share assignment) After the netatalk restart, umount succeeded without the -f.