The device is busy linux

3 Ways to Force Unmount in Linux Showing “device is busy”

In some situations when you try to unmount a filesystem especially NFS, it displays ‘device is busy’ message. This happens often when the NFS server has some issues (mainly unreachable) and you have a soft NFS mount.

There are different ways and options we can try out if normal NFS unmount fails. In this tutorial, I will explain how to perform a force unmount in Linux.

In our scenario, we have an NFS filesystem mounted on to /var/linoxide directory.

Let’s first use df command to display all mounted directories.

When we try to umount the remote partition, we have an error message. The following example shows the unmount fails because the device is busy:

1) With lsof

The lsof (list open files) command displays a list of all open files and the processes associated with them on a specific file system, directory, or device. By default, it lists all files, shared libraries, and directories that are currently open and provides as much information as possible about each of them.

Here we can use lsof command to find PID (process id) corresponding to our mount point and then kill that process.

Here we have the 3 PID of the process using the mounted directory. You can see vim command, which means that a file is being edited by the ‘linoxide’ user. You can inform the user to stop his action or kill the process.

Now, let’s see the results:

You can look that our user has stopped his modification but we still have bash command in execution but we don’t know why. We can now kill the two processes with kill command.

Now we will kill the first bash process

We can verify the result

We can see that one process is killed

Now let’s verify for the second process

Now let’s try to unmount the folder

Our action has automatically unmounted the folder but let’s check with df command.

From the output, we can see directory /mnt/nfs/linoxide_srv has been unmounted from the system.

2) With fuser

The fuser (find user processes) command helps to identify processes that are preventing you from unmounting file systems. It finds user processes that are associated with whatever files, directories, or file system mount points that you supply as command-line arguments.

We can use fuser command with -m option which lists all the processes accessing the files or mount point on the file system and the -v option which shows a result like ps command with PID, user and the executed command.

You can see the command in execution.

With fuser command, it is possible to directly kill the process in execution with -k option without kill command

Check the result

It seems that only the mount is in execution. Let’s try to unmount the folder

We don’t have any more error messages. Check the mount point

We can see that the /mnt/nfs/linoxide_srv folder has been unmounted as we want.

3) Lazy unmount

Umount command has an -l option to perform a lazy unmount (requires kernel 2.4.11 or later). The mount will be removed from the filesystem namespace (so you won’t see it under /mnt/nfs/linoxide anymore) 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.

Читайте также:  Как открыть windows shell

We can see that the folder is busy. Now let’s try to do a lazy unmount

We don’t have an error message. We will check if the command was being executed without error

Now let’s check the mount point

We can see that the mount point /mnt/nfs/linoxide_srv doesn’t appear again but as we said earlier, for example, our ‘linoxide’ user is still modifying his file, can create new files, etc. On the server, we can see the file that the user is modifying.

We can need to unmount a partition because of an emergency or simply to remove a device but a problem can occur because that device is busy. It is important to examine every process on the system before making a decision for the method to resolve the problem. The lsof and fuser commands make it easy to identify the processes that are preventing you from unmounting a file system. Finally, if you want to use a force unmount use -f option.

Conclusion

In this tutorial, we learned different options available when you are unable to umount in Linux and Unix-style systems. All mentioned force umount options explained should work on all Linux distributions like Ubuntu, Mint, etc.

If you have any questions or feedback, feel free to leave a comment.

Источник

Ошибка device or resource busy

Часто при работе с флешками, дисками, образами или другими подобными объектами может возникать ошибка device or resource busy. Она может выводится, когда вы пытаетесь отмонтировать внешний диск, раздел, а также при попытке переместить или удалить файл.

В этой небольшой статье мы рассмотрим, почему может возникать данная ошибка, а также пути её устранения. Конечно, в случае с флешкой вы можете просто вынуть её из компьютера, но это не решение, потому что высока вероятность потерять не сохранённые данные. Есть пути обхода этой проблемы.

Что означает «device or resource busy»?

Если переводить дословно с английского, то это сообщение означает, что устройство или ресурс занято. Если объяснять более подробно — файл, который вы пытаетесь удалить или диск, который нужно отмонтировать, ещё используется одной из запущенных программ.

Это могло произойти потому, что программа ещё не завершила свою работу, зависла, возникли какие-либо проблемы в процессе её работы. Это актуально как для файлов, так и для съёмных носителей.

Как исправить device or resource busy?

Самое первое, что можно посоветовать — закрыть программы, которые могут использовать этот файл или один из файлов на съёмном носителе. Например, если сейчас воспроизводится один из видеофайлов, то проигрыватель надо закрыть. И только поле этого пробовать ещё раз выполнять операции.

Если вы не знаете какая программа мешает вам выполнить операцию, то это можно очень просто узнать с помощью команды lsof. Просто выполните её и отсейте только те записи, которые относятся к точке монтирования вашего носителя:

lsof | grep /media/sergiy/83AE-2346

Чтобы отсеять нужные процессы в самой утилите, используйте опцию +D, так даже лучше, потому что она не будет показывать системные службы, а отобразит только программу, которую надо завершить:

lsof +D /media/sergiy/83AE-2346

Теперь вы можете видеть все процессы, которые используют файлы на нашем носителе, и завершить их с помощью команды kill. В нашем случае надо завершить плеер totem с PID 5616:

Также, чтобы посмотреть, какие процессы используют файл, можно использовать команду fuser:

fuser -vm /home/sergiy/83AE-2346

Здесь вы тоже увидите всю необходимую информацию: будет отображаться пользователь, от имени которого запущен процесс. Точно так же можно его завершить:

Если вы закрыли все программы, но это не помогло, можно попытаться очистить файловый кэш системы с помощью такой команды:

sync && echo 2 > /proc/sys/vm/drop_caches

Выводы

В этой небольшой статье мы рассмотрели, как бороться с ошибкой device or resource busy Linux. Как видите, её очень просто исправить, даже если по началу кажется, что совсем непонятно, что можно сделать.

Читайте также:  Windows создать запрос сертификат

Источник

Принудительно размонтировать раздел (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.

Источник

How to get over «device or resource busy»?

I tried to rm -rf a folder, and got «device or resource busy».

In Windows, I would have used LockHunter to resolve this. What’s the linux equivalent? (Please give as answer a simple «unlock this» method, and not complete articles like this one. Although they’re useful, I’m currently interested in just ASimpleMethodThatWorks™)

9 Answers 9

The tool you want is lsof , which stands for list open files.

It has a lot of options, so check the man page, but if you want to see all open files under a directory:

That will recurse through the filesystem under /path , so beware doing it on large directory trees.

Once you know which processes have files open, you can exit those apps, or kill them with the kill(1) command.

. Works for me. Thanks @camh

sometimes it’s the result of mounting issues, so I’d unmount the filesystem or directory you’re trying to remove:

I use fuser for this kind of thing. It will list which process is using a file or files within a mount.

Here is the solution:

  1. Go into the directory and type ls -a
  2. You will find a .xyz file
  3. vi .xyz and look into what is the content of the file
  4. ps -ef | grep username
  5. You will see the .xyz content in the 8th column (last row)
  6. kill -9 job_ids — where job_ids is the value of the 2nd column of corresponding error caused content in the 8th column
  7. Now try to delete the folder or file.

I had this same issue, built a one-liner starting with @camh recommendation:

  • awk grabs the PIDs.
  • tail gets rid of the pesky first entry: «PID».
  • xargs executes kill -9 on the PIDs. The -r / —no-run-if-empty , prevents kill command failure, in case lsof did not return any PID.

I experience this frequently on servers that have NFS network file systems. I am assuming it has something to do with the filesystem, since the files are typically named like .nfs000000123089abcxyz .

My typical solution is to rename or move the parent directory of the file, then come back later in a day or two and the file will have been removed automatically, at which point I am free to delete the directory.

This typically happens in directories where I am installing or compiling software libraries.

Читайте также:  Irc client console linux

Riffing off of Prabhat’s question above, I had this issue in macos high sierra when I stranded an encfs process, rebooting solved it, but this

Showed me the process and the PID (column two).

I had this problem when an automated test created a ramdisk. The commands suggested in the other answers, lsof and fuser , were of no help. After the tests I tried to unmount it and then delete the folder. I was really confused for ages because I couldn’t get rid of it — I kept getting «Device or resource busy»!

By accident I found out how to get rid of a ramdisk. I had to unmount it the same number of times that I had run the mount command, i.e. sudo umount path

Due to the fact that it was created using automated testing, it got mounted many times, hence why I couldn’t get rid of it by simply unmounting it once after the tests. So, after I manually unmounted it lots of times it finally became a regular folder again and I could delete it.

Источник

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 !)

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

Источник

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