Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to monitor disk mounts in Linux using C++?

Tags:

c++

linux

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!

like image 374
jamesmillerio Avatar asked Jan 29 '09 18:01

jamesmillerio


1 Answers

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.

like image 181
Alex B Avatar answered Sep 29 '22 01:09

Alex B