I need to find (in C or C++) the used space on a filesystem (Linux) when being provided only with the disk block device name and the partition number.
For most filesystems I can go:
- Craft a dev name as
/dev/<block><part>or/dev/<block>p</part>whichever exists - Search
/proc/mountsfor that device and get the mount point - Use
statvfs()on that mount point
Although that seems a bit long-winded it's adequate. However, there is a caveat to it:
My root is mounted from /dev/root rather than the real block device name. Except there isn't a /dev/root - the node doesn't exist. Now, I can dereference that to a /dev/<whatever> block name by using stat("/"...) to get the device ID and split it into major/minor numbers, then look up /sys/dev/block/<maj>:<min>/uevent for the DEVNAME= entry.
Keeping it a completely generic function the method would then expand to:
- Craft the right device name of
/dev/<block><part>or/dev/<block>p<part>, whichever exists - For each entry in
/proc/mounts:- Extract the mount point
- Get the major/minor pair from
stat() - Look up the parent device name from
/sys/dev/block/<maj>:0/uevent - Compare that device name with the block device name and the minor with the partition number
- If it's a match then get the used space from
statvfs()
That is getting really long-winded now, and I don't like it. Yes, it should work, but it is far from ideal.
So - is there a simpler interface for doing this? Some way of interacting directly with the mount table in the kernel? Some way of getting, for each mounted filesystem, the block device (major/minor would be fine), and the path it's mounted on (along with other information probably) in a struct?
I know there are mount() and umount() functions, but is there a "tell me what is mounted"() function?
dfhas the ability to look this up somehow, you might check the source code for that.dfjust callsstatvfs()on whatever mount point it finds in/etc/mtab. If the name of the block device in the first column of that file is incorrect,dfneither knows nor cares.