1

What is the best way of detecting and responding to filesystem mount events, say on /dev/sdb2? I'd like to be able to copy some of the contents of an SD card when it is inserted.

I've tried using watchdog to monitor the mount point, as well as to monitor /etc/fstab, but it doesn't detect the mounting or changes to fstab.

2

Following up on @Mark Setchell's udev and @MarkR's select suggestions, first make sure that the card will be automounted with an /etc/fstab entry similar to:

/dev/sdb1 /mnt/card extfat-fuse ro,defaults,nofail,user,auto 0 0

udev

A simple solution is to create a udev rule in /etc/udev/rules.d/99-local.rules:

ACTION=="add", KERNEL="sdb*", SUBSYSTEM=="block", RUN+="/bin/bash -c '/bin/date >> /tmp/udev.txt'"

The RUN script is run as root and it must complete quickly. The solution is global to the RaspberryPi. Outcomes can be tough to debug. The mounted file system might not be ready by the time the rule is executed.

select

Python's select module exposes POSIX and other OS-specific system calls to monitor I/O. One has to be a little careful in that neither the mounted directory nor the /proc/mounts files behave like regular files, so the utility of update times and tools like watchdog are limited.

import select f = open('/proc/self/mounts') pollster = select.poll() pollster.register(f, select.POLLERR | select.POLLPRI) events = pollster.poll(60*1000)

The pollster.poll(60*1000) call here will wait up to 60 seconds and return a list with pairs of file descriptor and event ids. If the list is non-empty, you can grep /proc/self/mounts for your mount point to act or poll again.

Using select might be more complex than udev, but it doesn't require root and it's simpler to debug. It does, however, require you ensure your polling always runs and to implement logic to handle updates.

1

I think it's possible to programmatically detect changes in mounted filesystems by monitoring the virtual file /proc/mounts using the poll API.

You can do that from Python using the "select" module, opening /proc/mounts etc.

Also see the "man" page for "proc" - which discusses the virtual file "mounts"

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.