【问题标题】:How can I determine the mount path of a given file on Linux in C?如何在 C 中确定 Linux 上给定文件的挂载路径?
【发布时间】:2016-11-17 16:06:03
【问题描述】:

我有一个任意文件,我想为其确定挂载点。假设它是 /mnt/bar/foo.txt,除了“正常”的 Linux 挂载点之外,我们还有以下挂载点:

[某些设备安装到] -> /mnt/bar [某些设备安装到] -> /mnt/other

我查看了 stat() 和 statvfs()。 statvfs() 可以给我文件系统 id,stat 可以给我设备的 id,但这些都不能真正与挂载点相关。

我在想我要做的是在任意文件上调用 readlink(),然后通读 /proc/mounts,找出与文件名最匹配的路径。这是一个好方法,还是我错过了一些很棒的 libc 函数?

【问题讨论】:

  • 不适用。这是在 C 中进行的,而不是使用 Linux 实用程序,我也不打算使用 fork/exec 或 system() 来调用这些程序。我想我可以看看这些程序的源代码。

标签: c linux


【解决方案1】:

您可以结合使用getfsent 来遍历设备列表,并使用stat 来检查您的文件是否在该设备上。

#include <fstab.h>    /* for getfsent() */
#include <sys/stat.h> /* for stat() */

struct fstab *getfssearch(const char *path) {
    /* stat the file in question */
    struct stat path_stat;
    stat(path, &path_stat);

    /* iterate through the list of devices */
    struct fstab *fs = NULL;
    while( (fs = getfsent()) ) {
        /* stat the mount point */
        struct stat dev_stat;
        stat(fs->fs_file, &dev_stat);

        /* check if our file and the mount point are on the same device */
        if( dev_stat.st_dev == path_stat.st_dev ) {
            break;
        }
    }

    return fs;
}

注意,为简洁起见,这里没有错误检查。 getfsent 也不是 POSIX 函数,但它是一个非常广泛使用的约定。它适用于甚至不使用/etc/fstab 的OS X。它也不是线程安全的。

【讨论】:

  • 谢谢!看起来 getmntent() 是 POSIX 的,也可以使用。
  • @Maxthecat 我不相信getmntent 是 POSIX 并且它在 BSD(或 OS X)上不存在。 BSD 有getmntinfogetfsstat。它们可能是 POSIX 2 或 3 函数,我没有相关文档。
猜你喜欢
  • 2015-05-09
  • 1970-01-01
  • 2013-05-13
  • 2010-10-02
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多