Стандартная проблема с mount/umount «device or recourse is busy»
Есть одна проблемка, думаю, для неё должно быть стандартное решение. Сразу упомяну — речь идёт о встроенной системе, где максимум, что есть — busybox. Так вот задачка в двух словах: есть устройство с SD-слотом, когда карточка вставлена, надо её примонтировать и сказать другой программе, что карта есть и можно на неё писать, ну и когда карту вытащили, надо соответственно её отмонтировать и сказать другой программе, что карты собсна нету.
Контролирую, что карта вставлена, по появлению /sys/block/mmcblk0. Когда директория, появляется монтирую с:
mount( /dev/mmcblk0p1, /mnt/SD, «vfat», MS_SYNCHRONOUS, NULL);
Когда системная директория пропадает, то отмонтирую с:
umount2( /mnt/SD, MNT_FORCE );
Всё работает хорошо, пока карта не вытаскивается во время записи другой программой. В этом случае карту невозможно отмонтировать. Максимум, что нашёл в гугле это то, что в таком случае надо «убить» программу с открытым доступом к карте, а после этого отмонтировать. Неужели нет другого решения?
How to unmount a busy device
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?
11 Answers 11
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:
NOTE:
- 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.
- Do execute these commands when not inside mounted Folder/Drive/Device.
If possible, let’s locate/identify the busy the process, kill the process and then unmount the samba share to minimize damage.
lsof | grep ‘ ‘ (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)
: See if this gets you started. tldp.org/HOWTO/SMB-HOWTO-8.html – Frank Tudor Oct 24 ’11 at 17:17
Make sure that you aren’t still in the mounted device when you are trying to umount.
/Documents on Solaris 11; but Documents had subfolders and it was the issue. – Dani Aya Jan 29 at 20:44
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.
Avoid umount -l
At the time of writing, the top-voted answer recommends using umount -l .
- 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:
- All pending data has been written to disk
- All future write attempts will fail
- 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!
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:
- Temporarily duplicate the mountpoint with mount -o bind /media/hdd /mnt to another location
- Hide the original mount point and block the namespace:
- The original namespace hidden (no more files could be opened, the problem can’t get worse)
- 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:
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:
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.)
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.umount: target is busy
I have mounted /dev and immediately tried to unmount:
I have read that fuser can kill processes accessing the mount point, but I would like to understand what is happening in this simple case. Acording to the lsof output does something use the mountpoint as current working directory (cwd)?
I do not want to use lazy unmount.
1 Answer 1
You used rbind to mount a filesystem and submounts. In order to unmount a filesystem, you must unmount its submounts first (and the same for their submounts, recursively). But take care!
Without the first command, you risk unmounting all the sub-mounts on the source, due to mount propagation. In this case that means all the sub-mounts of /dev , which would have bad effects on your running system ;-).
Basically mount propagation is a massive pit-trap waiting for you to fall into it :-). It seems like it would have been better if bind mounts disabled it by default.
kdevtmpfs is the kernel thread that maintains devtmpfs. It does not prevent unmounting devtmpfs. This is because the kernel thread runs on a separate mount (like a bind mount). You can’t see that original mount; it is in a separate mount namespace. If you want to try and work out why kdevtmpfs shows up in lsof , I don’t know, maybe consider that a separate question.
umount device is busy — пока перегружается сервер
Здравствуйте. Вот, как всегда весь интернет в ответах не в тему. Итого, ситуация: umount
говорит «device is busy». lsof и fuser молчат — ну нету открытых файлов. Тем не менее device is busy. Вопрос, что делать? umount -f ничего не даёт. Последнее средство: umount -l. Конечно, устройство как-бы отмонтировалось, но, тем не менее, осталось busy.
Вопрос, собственно, в том, как всё-таки сделать нормальный force unmount, то есть не выявить и закрыть всё, что мешает, а потом нормально отмонтировать, или сделать вид, что отмонтировали, с последующим освобождением всего остального когда-нибудь. А именно отмонтировать здесь и сейчас, невзирая на все открытые файлы. Возможно?
Возможно что-то примонтировано в нужном каталоге. Сделай mount | grep
. Возможно ты в этом каталоге (pwd чтоб показать). Выйди со всех терминалов, ССШ, один оставь и перейди в /, тогда и пробуй.
Возможно что-то примонтировано в нужном каталоге
Возможно ты в этом каталоге (pwd чтоб показать)
lsof это показывает.
Да и вопрос-то в чистом виде такой: можно ли сделать действительно принудительное размонтирование, несмотря на открытые файлы и наличиствующие глюки? Если я, допустим, не хочу находить и убивать процессы, удерживающие файлы, или не могу по какой-то причине этого сделать.
можно сделать lazy umount. но это только видимость, т.к. после ребута фс все равно будет восстанавливаться. у меня было разок такое, топик открывал тут, так и не выяснил что это было.