I want to be sure that a removable hard drive (USB, but this shouldn't matter) is safe to remove. Let's say this drive is sdb.

Obviously I need to make sure that there is no mounted filesystem on that drive. grep /dev/sdb /proc/mounts will tell me.

But that's not the whole story. For example, if there is an LVM physical volume on sdb, I need to deactivate all volume groups that contain a physical volume located on sdb (lvchange -an my_volume_group/my_logical_volume then vgchange -an my_volume_group). If there is a RAID volume, I may need to deactivate it (mdadm -S), or I may want to mark the component as failed (mdadm -f).

Is there a way to list all the ways a disk is in use? For my use case, I need to be confident that this list is exhaustive, so that I can unplug the device if the list is empty.


2 Answers 2


If you are able to open a block device O_EXCL, it isn't in use by the kernel (O_EXCL takes a device lock in this particular case). lsof (/proc scanning) should find any other users (VMs might have the device open, and often fail to open exclusively).


+1 for Gabriel's answer - O_EXCL is exactly the solution I used in this scenario. Here's the Perl function I wrote to check if a device is in use:

use Fcntl;
use Errno;

sub device_in_use($)
  my $device = shift;
  # open with O_EXCL returns EBUSY if a device is in use
  # http://www.kernel.org/doc/man-pages/online/pages/man2/open.2.html
  return $!{EBUSY} if (!sysopen my $fh, $device, O_EXCL);
  close $fh;
  return 0;

Beware though that it doesn't have proper error handling - it expects the device to exist and that you have root permissions.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .