Question

I'm reading the source code of docker,and it checks if one directory has been mounted by such a test condition,what's the principle behind it?

func Mounted(mountpoint string) (bool, error) {
    mntpoint, err := os.Stat(mountpoint)
    if err != nil {
        if os.IsNotExist(err) {
                return false, nil
        }
        return false, err
    }
    parent, err := os.Stat(filepath.Join(mountpoint, ".."))
    if err != nil {
        return false, err
    }
    mntpointSt := mntpoint.Sys().(*syscall.Stat_t)
    parentSt := parent.Sys().(*syscall.Stat_t)
    return mntpointSt.Dev != parentSt.Dev, nil
}
Was it helpful?

Solution

From the stat(2) man page on Linux:

The st_dev field describes the device on which this file resides. (The major(3) and minor(3) macros may be useful to decompose the device ID in this field.)

So what the code in question is doing is invoking the stat system call on the directory and its parent and checking whether they reside on different devices. This can only be true if they are on different file systems, which would indicate that the directory in question is a mount point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top