c - libblkid 仅适用于 root 并且以 root 身份运行后

标签 c linux blkid

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

我创建了一个 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;
}

当我以普通用户身份运行时,它不显示任何设备/分区和类型。 所以,我尝试以 root 身份运行,我终于看到了设备、分区和类型。 当我返回用户时,如果我再次运行,我可以看到与 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 身份运行它之后,信息会被缓存。之后,当您以非 root 身份再次运行时,将检索该信息。

关于c - libblkid 仅适用于 root 并且以 root 身份运行后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56450829/

相关文章:

c - 根据每个元素的频率对数组元素进行排序

c - 编写了一个打印素数的程序,但没有得到所需的输出。我哪里出错了?

我可以在不使用 c 中的循环的情况下将 1d 数组复制到 2d 结构中吗?

linux - 环境输出中缺少主机名

linux - Mongo Shell 坏了

linux - 使用来自主机的 CA Trust Bundle 构建 Docker

linux - BLKID 是如何分配的?

c - 关于 malloc 代码中使用的类型和变量的说明