How do I check whether a CD is currently in use on Linux?

2

How do I check whether a CD is in use before I remove it from the VM? It's currently mounted on /dev/sr0 on a Ubuntu 14.04 machine and I need to unmount it for datastore migration.

I know it's not being written to, but I need to know if it's being read from.

wintermuted

Posted 2018-09-17T11:11:26.280

Reputation: 33

1What hypervisor are you using? – Xyon – 2018-09-17T11:39:34.797

vSphere, but I don't think it matters much. All I know is that VMWare tells me that it wants to unmount the disk when I try to remove it, but before I remove the CDs from my production machines I want to know if they CDs are being accessed actively. – wintermuted – 2018-09-17T12:00:48.577

Simples way would be to tell the Ubuntu VM to unmount it. If that succeeds, it's currently not in use. – dirkt – 2018-09-17T12:31:54.053

Answers

1

The only way to do this properly is to try to unmount the CD inside the VM.

The general procedure I typically use is:

  1. Check if it's mounted at all, preferrably run as root:

    grep /dev/sr0 /proc/self/mounts
    

    If that spits out any text, then the CD is mounted and may be in use (but isn't safe to remove yet even if it isn't in use), otherwise you can assume it's unused unless you have CD-burner software open.

  2. Attempt to unmount it (must be done as root):

    umount /dev/sr0
    

    If that succeeds without error, you can be certain at this point the CD is not in use and can safely remove it on the hypervisor side. If it complains about /dev/sr0 not being mounted, recheck the first step, otherwise, go on to the next step.

  3. Figure out what was using it (also must be done as root, and you may have to install the fuser command):

    fuser -m $(grep /dev/sr0 /proc/self/mounts | cut -f 2)
    

    This will figure out where it's mounted, and then spit out one line for each file in use, starting with the name of the file, followed by a space separated list of PID's that are using the file. You can then look up what processes those PID's belong to in most system monitoring software like top. If you don't care what they are, you can add -k -TERM before the -m to that above command, and it will send a SIGTERM to all of the processes for you (equivalent to calling kill on each PID). Once all of those have been dealt with, you can repeat step 2, and the umount command should work.

Note that this approach assumes that no mount namespaces are involved, which will usually be true unless you are using containers (in which case, you may have to go through all these steps in each running container).

Austin Hemmelgarn

Posted 2018-09-17T11:11:26.280

Reputation: 4 345