挂载点归属

huangapple go评论135阅读模式
英文:

Mount point attribution

问题

我正在阅读Docker的源代码,它通过以下测试条件来检查一个目录是否已经挂载,这背后的原理是什么?

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
}

这段代码首先通过os.Stat函数获取给定目录的文件信息,如果返回的错误是os.IsNotExist,则说明目录不存在,返回false。如果返回其他错误,则返回false和错误信息。

接下来,它通过os.Stat函数获取给定目录的父目录的文件信息。如果返回错误,则返回false和错误信息。

然后,它分别获取目录和父目录的syscall.Stat_t结构体,该结构体包含了文件的设备号(Dev字段)。

最后,它比较目录的设备号和父目录的设备号,如果它们不相等,则说明目录已经被挂载,返回true;否则,返回false

这个函数的原理是通过比较目录和父目录的设备号来判断目录是否已经被挂载。如果它们的设备号不相等,说明目录已经被挂载到了不同的设备上。

英文:

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
}

答案1

得分: 5

从Linux上的stat(2)手册页面上可以看到:

st_dev字段描述了该文件所在的设备。(major(3)minor(3)宏可能对将该字段中的设备ID分解为有用。)

所以,问题中的代码正在对目录及其父目录调用stat系统调用,并检查它们是否位于不同的设备上。只有当它们位于不同的文件系统上时,这才可能为真,这表明所讨论的目录是一个挂载点。

英文:

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.

huangapple
  • 本文由 发表于 2013年10月22日 17:23:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/19513874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定