3

I want to somehow get notified if a mount or unmount occurs for a USB drive.

At the moment I use udev and then wait for x seconds for a new entry in /proc/mounts. This works ok if the mounting is automatic. However this won't work if the user unmounts/mounts the device manually.

Is there a way to catch those events?

1

If polling is okay you could look at the time on mtab:

import time, os
last = None
current = None

for x in range(0,60):
    if last == current:
        current = os.stat('/etc/mtab').st_mtime
        print('Current Updated: ', current)
        print('No Changes...')
    else:
        last = current
        print('Last Updated: ',last)
        print('Something was mounted or unmounted')
    time.sleep(1)

You could also use filecmp or difflib to see if there are any changes, and parse what kind of changes occurred if you go with this route.

  • I am not sure why the other user deleted their answer. They brought up a really good point with looking at /proc/mounts and /proc/self/mounts ... mtab is a symobolic link and might not be as up to date, but more software friendly, whereas /proc/mounts will have everything, or as far as I understand it. – jmunsch Dec 1 '14 at 13:49
  • 1
    Yes, as kernel devs said when they removed KOBJ_MOUNT & KOBJ_UNMOUNT from kernel uevents, /proc/mounts is the way to go. I would definitely not rely on mtime as it is constantly updated even if nothing is mounted/unmounted (run stat -c %Y /proc/mounts in terminal, wait a few seconds, run it again). See also the answers here. – don_crissti Dec 1 '14 at 17:30
  • A lot of distributions have /etc/mtab as a symbolic link to /proc/mounts. I don't know what determines the mtime of /proc/mounts, but in many cases it's the current date. The content read from /proc/mounts is generated on the fly, it isn't rebuilt each time the data would change, so there's no reason why the mtime of /proc/mounts would be significant. – Gilles Dec 2 '14 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.