views:

403

answers:

2

I'm using Linux Inotify to detect FS events on my program.

How could I be notified when a device is mounted on a monitored directory?

+4  A: 

I don't think you can do it with inotify. Here is the method though:

  1. Read uevents from kernel via a Netlink socket and filter out those where "ACTION" is not "mount".
  2. Read and parse "/proc/mounts" when you get an event with a "mount" action.
  3. Find a record for a mount point with device that was just mounted and filter it out if it's not the directory you are watching.
Alex B
The alternative is to put an `inotify` watch on `/etc/mtab`, and do the same kind of parsing as you would do on `/proc/mounts`. But this is much more fragile.
Michiel Buddingh'
+1  A: 

If you don't mind depending on fairly new libraries, you could use libudev for the first step.

Again, if you don't mind depending on new stuff and DBus, DeviceKit-Disks will do all of this for you, too. You'd hook into the DeviceChanged signal, and then look at the device-mount-paths property.

RAOF