libblkid 仅适用于 root 和 运行 之后的 root

libblkid only works with root and after running as root

这是我见过的最奇怪的东西(实际上,它有一个很好的解释)。

我创建了一个 C 代码来列出分区及其自身的类型:

char *get_luks_partition(void) {
    blkid_dev dev;
    blkid_cache cache;
    blkid_dev_iterate iter;
    const char *devname = NULL;
    char *ret = NULL;
    const char *type = NULL;

    if (blkid_get_cache(&cache, NULL))
        return NULL;
    blkid_probe_all(cache);

    iter = blkid_dev_iterate_begin(cache);

    while (!blkid_dev_next(iter, &dev)) {
        devname = blkid_dev_devname(dev);
        type = blkid_get_tag_value(cache, "TYPE", devname);

        if (type)
            printf("dev: %s type: %s\n", devname, type);

        if (type && !strcmp(type, "crypto_LUKS")) {
            ret = (char *) devname;
            break;
        }
    }

    blkid_dev_iterate_end(iter);

    return ret;
}

当我 运行 作为普通用户时,它不显示任何 device/partition 和类型。 所以,我尝试以 root 身份 运行,我终于看到了设备、分区和类型。 当我 return 给用户时,如果我再次 运行 ,我可以看到与 root 相同的输出。 查看顺序:

$ ./main 
dev: /dev/sr0 type: udf

$ sudo ./main 
dev: /dev/vda1 type: vfat
dev: /dev/vda2 type: xfs
dev: /dev/vda3 type: crypto_LUKS

$ ./main 
dev: /dev/vda1 type: vfat
dev: /dev/vda2 type: xfs
dev: /dev/vda3 type: crypto_LUKS

有谁知道发生了什么事吗?

来自 BLKID(8) 手册页:

The libblkid library is used to identify block devices (disks) as to their content (e.g. filesystem type) as well as extracting additional information such as filesystem labels/volume names, unique identifiers/serial num‐ bers. A common use is to allow use of LABEL= and UUID= tags instead of hard-coding specific block device names into configuration files.

...

Note that blkid reads information directly from devices and for non-root users it returns cached unverified information.

来自 LIBBLKID(3) 手册页:

The high-level part of the library keeps information about block devices in a cache file and is verified to still be valid before being returned to the user (if the user has read permission on the raw block device, otherwise not). The cache file also allows unprivileged users (normally anyone other than root, or those not in the "disk" group) to locate devices by label/id. The standard location of the cache file can be overridden by the envi‐ ronment variable BLKID_FILE.

因此,在您 运行 以 root 身份使用它之后,信息将被缓存。之后,当您再次 运行 作为 non-root.

时,会检索该信息