Linux – Are two subdirectories with the same root guaranteed to be on the same mounted file system

filesystemslinuxmountrename

A cpp file I'm working with creates a directory, i.e. mkdir( path, ... ), where path comes from an environment variable (e.g. getenv( "FOO" );).

As an example, say $FOO is /foo, and path, created above, is `/foo/newPath/'.

For my question scenario, it is possible that /foo/oldPath/ exists and has content (assume no further subdirectories), in which case I want to move files from /foo/oldPath/ to /foo/newPath.

My question is: because /foo/newPath/ is created as a subdirectory of $FOO, i.e. /foo/newPath/ and /foo/oldPath/ have the same parent directory, is it then guaranteed that both directories are on the same "mounted file system"? My understanding of mount points and file systems on Linux is tenuous at best.

The context behind this question is: if /foo/newPath/ and /foo/oldPath/ are guaranteed to be on the same mounted file system, I can use rename() to more easily perform the file movement than other alternatives. The man page of the function says that it will fail if oldPath and newPath are not on the same "mounted file system."

Best Answer

They are not guaranteed that. It is possible that /foo/oldPath is a mount point.

This can, however, be easily checked by running mount | grep 'on /foo/oldPath' No output should indicate that the oldPath directory is not a mount point.

You will need to be more careful if you are using nested directories, since you can have a mount point anywhere.

I'm not sure whether this is automated, but it's worth noting that the 3rd field from mount (space-separated) is the mount point for each line, so utilizing an cut -d ' ' -f 3 could be used to extract the path (should you need to verify it's not just a substring of another mount point, like /foo/oldPath/nested/mountPoint)

If you'd like to translate this into C/C++ code, you may be able to use system("mount | grep 'on /foo/oldPath'"), but I won't swear by that. You may have better luck on StackOverflow for more implementation detail there if you need it.

Related Question