Linux umount target is busy

umount: устройство занято. Почему?

При беге umount /path я получаю:

Файловая система огромна, поэтому lsof +D /path это нереальный вариант.

lsof /path , lsof +f — /path И fuser /path все не возвращает ничего. fuser -v /path дает:

что нормально для всех неиспользуемых смонтированных файловых систем.

umount -l и umount -f не достаточно хорош для моей ситуации.

Как мне выяснить, почему ядро ​​считает эту файловую систему занятой?

Кажется, причиной моей проблемы nfs-kernel-server был экспорт каталога. nfs-kernel-server , Вероятно , идет позади обычных открытых файлов и , таким образом , не перечислены lsof и fuser .

Когда я остановился, nfs-kernel-server я мог umount каталог.

Чтобы добавить BruceCran «s комментарий выше, причина для моего проявления этой проблемы только сейчас был несвежий петлевой крепление. Я уже проверил вывод fuser -vm / lsof +D , mount и cat /proc/mounts проверил, работал ли какой-то старый nfs-kernel-сервер, отключил квоты, попытался (но потерпел неудачу) a umount -f и почти смирился с тем, что отказался от времени безотказной работы 924 дней, прежде чем наконец проверить вывод из losetup и нахождения двух устаревших сконфигурировано-но-не-смонтированных шлейфов:

В сообщении на форуме Gentoo также перечислены файлы подкачки как потенциальный преступник; хотя обмен файлами, вероятно, довольно редок в наши дни, проверить выходную информацию не помешает cat /proc/swaps . Я не уверен, могли ли когда-нибудь квоты помешать демонтировать — я держался за соломинку.

Вместо того, чтобы использовать lsof для обхода файловой системы, просто используйте общий список открытых файлов и создайте его. Я считаю, что этот возврат должен быть быстрее, хотя и менее точным. Это должно сделать работу.

Для меня оскорбительным процессом был демон, запущенный в chroot. Потому что это было в chroot, lsof и fuser не нашел бы его.

Если вы подозреваете, что у вас есть что-то, работающее в chroot, sudo ls -l /proc/*/root | grep chroot вы найдете виновника (замените «chroot» на путь к chroot).

Открытые файлы

Процессы с открытыми файлами являются обычными виновниками. Показать их:

Преимущество использования /dev/ вместо /mountpoint : точка монтирования исчезнет после umount -l или может быть скрыта наложенным монтированием.

fuser Также можно использовать, но на мой взгляд, lsof есть более полезный вывод. Однако fuser это полезно, когда дело доходит до уничтожения процессов, вызывающих ваши драмы, чтобы вы могли продолжить свою жизнь.

Список файлов (см. Предостережение выше):

Интерактивно уничтожать только процессы с открытыми для записи файлами:

После перемонтирования только для чтения ( mount -o remount,ro ) можно (r) убить все оставшиеся процессы:

точки монтирования

Виновником может быть само ядро. Другая файловая система, смонтированная в той файловой системе, к которой вы пытаетесь umount , вызовет горе. Проверить с:

Для петлевых монтировок также проверьте вывод:

Анонимные иноды (Linux)

  • Временные файлы ( open с O_TMPFILE )
  • Inotify часы
  • [Eventfd]
  • [Eventpoll]
  • [Timerfd]

Это самый неуловимый тип покемона, и появляются в lsof «s TYPE столбец как a_inode (который без документов на lsof странице человека ).

Они не появятся lsof +f — /dev/ , поэтому вам нужно:

Для процессов уничтожения, содержащих анонимные inode, смотрите: Список текущих наблюдений inotify (pathname, PID) .

Чтобы fuser мог сообщить о PID, которые держат монтируемое устройство открытым, вы должны использовать -m

У нас есть собственная система, в которой корневая файловая система обычно доступна только для чтения. Иногда, когда файлы должны быть скопированы, перемонтируется чтение-запись:

А потом перемонтировал обратно:

На этот раз, однако, mount продолжал давать mount: / is busy ошибку. Это было вызвано процессом, содержащим открытый дескриптор файла, который был заменен некоторой командой, которая выполнялась, когда файловая система находилась в режиме чтения-записи. Важной строкой из lsof — / вывода является (имена были изменены):

Обратите внимание DEL на вывод. Простая перезагрузка процесса, держась за удаленный файл, решила проблему.

lsof и fuser ничего не дал мне тоже.

После процесса переименования всех возможных каталогов в .old и перезагрузки системы каждый раз, когда я вносил изменения, я обнаружил один конкретный каталог (связанный с postfix), который отвечал за это.

Оказалось, что я когда — то сделал симлинк от /var/spool/postfix до /disk2/pers/mail/postfix/varspool того , чтобы минимизировать запись на диск на SDCARD основе корневой файловой системы (Штекер Шива).

С этой линке, даже после остановки postfix и dovecot услуг (как ps aux и netstat -tuanp ничего не связанный показывают) я был не в состоянии unmount /disk2/pers .

Когда я удалил символическую ссылку и обновил файлы конфигурации postfix и, dovecot чтобы они указывали непосредственно на новые каталоги, /disk2/pers/ я смог успешно остановить службы и unmount каталог.

В следующий раз я посмотрю более внимательно на вывод:

Приведенная выше команда рекурсивно выведет список всех символических ссылок в дереве каталогов (здесь начиная с /var ) и отфильтрует те имена, которые указывают на конкретную целевую точку монтирования (здесь disk2).

Читайте также:  Exact audio copy linux

У меня была эта проблема, и оказалось, что на заднем плане были активные сеансы экрана, о которых я не знал. Я подключился к другому активному экранному сеансу, а его оболочка даже в данный момент не находилась в смонтированном каталоге. Убийство тех других сессий оболочки решило проблему для меня.

Просто подумал, что поделюсь своим решением.

Сегодня проблема была в открытом сокете (конкретно tmux ):

У меня есть пара bind и overlay монтирует под моим горе, блокировали меня, проверьте автодополнению на точку монтирования , которую вы хотите отключить. Я подозреваю, что это было наложение, в частности, но могло быть и связыванием

Это скорее обходной путь, чем ответ, но я выкладываю его на случай, если это кому-нибудь поможет.

В моем случае я пытался изменить LVM, так как хотел увеличить раздел / var, поэтому мне нужно было его размонтировать. Я попробовал все комментарии и ответил в этом посте (спасибо всем и особенно @ ole-tange за их сбор) и все равно получил ошибку «устройство занято».

Я пытался убить большинство процессов в порядке, указанном в уровне запуска 0, просто на случай, если порядок был уместен в моем случае, но это тоже не помогло. Поэтому я создал собственный уровень выполнения (объединяющий вывод команды chkconfig в новые команды chkconfig —level), который был бы очень похож на 1 (однопользовательский режим), но с сетевыми возможностями (с сетью ssh и xinet).

Поскольку я использовал redhat, уровень запуска 4 помечен как «неиспользуемый / определенный пользователем», поэтому я использовал его и запустил. init 4 В моем случае это было нормально, так как мне нужно было перезагрузить сервер в любом случае, но, вероятно, это будет так кто-нибудь настраивал диски.

Источник

Принудительно размонтировать раздел (umount — device is busy)

Иногда не получается размонтировать раздел, так как выходит ошибка:

umount — device is busy

umount: /mnt/disk: device is busy

Тогда его можно размонтировать принудительно командой

umount -l /mnt/disk

umount -f /mnt/disk

авторынок

Похожие материалы (по тегу)

234 комментарии

Стартовый касательно довольно расхожих видов продвижения касательно коммерции есть навесная рекламное объявление, которую реально разместить на публичном локации плюс привлекать интересующихся клиентов. Предприятие LowCostPrint уже из течении многих лет занимается форматную печатью большой трудности также сумеет воплотить задание в постижимым цене в Московской области. В онлайн магазине баннер 6х3 пользователь сможет выбрать интересующий модификацию баннера: рекламные растяжки, интерьер оттиск, ненастоящие фасады, стенды, постпечатная печать, наклейки, пропечатка по сетке и другие форматы широкого печати.
Определиться с подходящим вариантом клиентам помогут наши опытные менеджеры, те что у телефонном распорядке дадут полноценный ответ на всяческих неотложных вопросы, укажут счет плюс посодействуют осущетсвить широкоформатную печать именно по онлайн ресурс. Трудясь на нашем оборудовании также из https://баннер-москва.рф/ прямыми снабженцами, наш магазин гарантируем новым покупателям отличное свойства, быстрая реализация, формирование любых размеров и верную тон!

Error 523 origin is unreachable

Error 523 origin is unreachable

Error 523 origin is unreachable

I’m not sure where you’re getting your information, but good topic.
I needs to spend some time learning much more or understanding more.
Thanks for magnificent info I was looking for this information for my mission.

Источник

Busy Device on Umount

I often experience a problem to umount a directory:

There are many reasons why the device is busy. Sometimes there are processes running which have open locks on it, sometimes there are other directories mounted on top of /mnt/dir .

What are the steps to check why a directory couldn’t be unmounted.

I know there are many reasons, but it’s ok if you explain a specific solution.

[X] running processes on mounted volumes.
[X] another volume is mounted on top of a volume we want to unmount
[_] NFS locks the volume we want to unmount

6 Answers 6

The way to check is fuser -vm /mnt/dir , which must be run as root. It will tell you which processes are accessing the mount point.

An alternative is lsof /mnt/dir , which will show each open file on the mount. Again best run as root.

You can run either of these as non-root, but then the output will be limited to your processes—ones from other users will just be silently not shown, even though they will prevent unmounting the filesystem.

Example:

The «access» field tells you how its being accessed. In this case, the kernel has it in use as a mount (duh, but unmount will be OK with only this). bash has it as the current working directory (will have to cd to a different directory before unmount) and gvim both has the current directory and has a file open (will need to close that gvim).

In this output, you can see the current directories for both bash and gvim (as type DIR ). You can also see which file gvim has open for write.

How to force the issue:

fuser has a -k option which will send a signal (default: SIGKILL ) to each process using the mount. This is a rather forceful way to stop the mount from being busy. (And of course, be careful of what you SIGKILL !)

Читайте также:  Настройка nvidia x server settings linux ubuntu

umount has an -l option to perform a lazy unmount. The mount will be removed from the filesystem namespace (so you won’t see it under /mnt/Zia/src anymore, in the example) but it stays mounted, so programs accessing it can continue to do so. When the last program accessing it exits, the unmount will actually occur.

There is one final fixable cause of unmount failing, and that’s an NFS server going down. Here you can use umount -f , but you risk data loss if you do so. (The client may have cached writes that haven’t been confirmed by the server yet, and those writes will be discarded. Apps, however, have already been told the write is successful.)

Источник

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?

14 Answers 14

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

If possible, let us locate/identify the busy process, kill that process and then unmount the samba share/ drive 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)

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.

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:

  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!

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

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.

Читайте также:  Как посмотреть сколько бит система windows 10

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.

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.

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.

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. Return Value

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

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 :

As you can notice, even lsof returns nothing.

Then I had the idea to type this :

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.

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:

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.

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:

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.

Источник

Оцените статью