Given a path to a file or directory, how can I determine the mount point for that file? For example, if /tmp
is mounted as a tmpfs
filesystem then given the file name /tmp/foo/bar
I want to know that it's stored on a tmpfs
rooted at /tmp
.
This will be in C++ and I'd like to avoid invoking external commands via system()
. The code should be robust--not necessarily against deliberate tampering but definitely in the face of nested mountpoints, symlinks, etc.
I haven't been able to find a simple system call to do this. It looks like I'll have to write the check myself. Here's a rough outline of what I'm planning.
- Canonicalize the file name a la the
readlink
shell command. How? - Read
/etc/mtab
withgetmntent()
& co. - Determine the corresponding mount entry for the file. How?
For #1 is there a simple system call or do I need to read each directory component of the path and resolve them with readlink(2)
if they are symlinks? And handle .
and ..
myself? Seems like a pain.
For #3 I've got various ideas on how to do this. Not sure which is best.
open()
the file, its parent, its parent's parent, etc. usingopenat(fd, "..")
until I reach one of the/etc/mtab
entries. (How do I know when I do?fstat()
them and compare the inode numbers?)- Find the longest directory name in the mount table which is a substring of my file name.
I'm leaning towards the first option but before I code it all up I want to make sure I'm not overlooking anything--ideally a built-in function that does this already!