tags:

views:

412

answers:

2

I am currently constructing a Carputer front end and one function that it needs is to be able to recognize when external media is inserted, such as USB/SD memory sticks or iPods. Upon their insertion, I will then scan the device for music/video/images and add them to the media library. Alternately, I need to know when these devices are removed so that I can remove the added items from the currently available media.

My question is, what is the best way to monitor disk insertions/removals in a Linux environment using C++?

I could monitor the /media folder for when Linux mounts the disks automagically, but is this the best way to accomplish the task? Thanks for any insight!

+5  A: 

You can read kernel uevents from a NetLink socket. It provides events about device adding/removal, mount/umount.

-- Netlink

A daemon listening to the netlink socket receives a packet of data for each hotplug event, containing the same information a usermode helper would receive in environment variables.

The netlink packet contains a set of null terminated text lines. The first line of the netlink packet combines the $ACTION and $DEVPATH values, separated by an @ (at sign). Each line after the first contains a KEYWORD=VALUE pair defining a hotplug event variable.

[...]

ACTION

The current hotplug action: "add" to add the device, "remove" to remove it. The 2.6.22 kernel can also generate "change", "online", "offline", and "move" actions.

You probably want to monitor mount and umount actions. Note that event does not give you either device node or the actual mount point, only device's sysfs node. If device nodes management and mounts management are handled by an external process (e.g. udev), you'll have to find out the device node and a mount point yourself using major and minor device numbers and /proc/mounts.

Alex B
+3  A: 

If hald is running on your system, you can watch for a org.freedesktop.Hal.Manager.DeviceAdded DBUS signal.

Mounts are a bit tricker to watch for, if you not in control of the mounter, you might have to poll /proc/mounts for that. I don't see any way to get notifications out of pmount or gnome-volume-manager. KDE 4's Solid may provide an interface for that, but I haven't dug into it.

ephemient
Unfortunately, the target system won't have Gnome or KDE running since it has limited memory and processing power.
Bit Destroyer