0

I know that there is /dev/disk/by-id/ folder which contains links to /dev/sd* elements. I'd like to know, is there any way to get by-id element pointing to, for example, /dev/sda.

P.S.: yeah, I know that I can loop through elements in by-id folder and /dev/sd*, so that I can compare serial numbers and match them. But is there any better way?

EDIT: sorry for my mistake. It should be done in C/C++. UUID's were mentioned. That would be great, they are unique and so on, but how can I collect all the UUID's of one hdd? I mean the main, pointing to sda, for example, and partition UUID's, pointing to sda1, sda2 and so on.

4

2 回答 2

1

我很抱歉迟到的答复。

我的问题是错误的,我不需要/dev/sd*元素来获取/dev/disk/by-id/元素。

我使用了libudev并得到了这些元素:

#include <libudev.h>

...

struct udev *udev;
udev = udev_new();

udev_enumerate *enumerate;
enumerate = udev_enumerate_new(udev);

udev_list_entry *udev_entries;
udev_list_entry *dev_list_entry;
udev_device *dev;

udev_enumerate_add_match_subsystem(enumerate, "block");
udev_enumerate_scan_devices(enumerate);
udev_entries = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(dev_list_entry, udev_entries)
{
    const char* path = udev_list_entry_get_name(dev_list_entry);
    dev = udev_device_new_from_syspath(udev, path);
    const char* bus = udev_device_get_property_value(dev, "ID_BUS");
    const char* type = udev_device_get_property_value(dev, "ID_TYPE");

    if (!bus || !type)
        continue;

    // strncmp return 0 if equal
    if (!(strncmp(bus, "ata", 3) &&
            !strncmp(type, "disk", 4))
        continue;

    // i wanted to get only partitions, so parent is empty
    udev_device *parent = 
        udev_device_get_parent_with_subsystem_devtype(dev, "block", "disk");
    if (!parent)
        continue;

    // get /dev/disk/by-id/...-partX
    struct udev_list_entry* devlinks = udev_device_get_devlinks_list_entry(dev);
    std::string partition(udev_list_entry_get_name(devlinks));
    // now we have /dev/disk/by-id/...-partX in partition and can save it somewhere
}

PS:我在基于 LFS 的特殊发行版中使用过它,它的/dev/disk/by-id/名称中确实有序列号。

于 2015-12-11T14:09:09.230 回答
0

嗯,id 不是您通常用来唯一标识分区的东西。如果 UUID 是一个选项,您可以这样做:

# blkid  /dev/sdf1
/dev/sdf1: UUID="1cdc1aec-5bde-45d4-9202-bc8fdec378f1" TYPE="ext2" 

blkid支持一些命令行选项,为您提供不同级别的详细程度和格式。

您通常不使用 id 的原因是它们不能保证是唯一的。UUID 通常是。

如果它必须是 id,遍历 /dev/disk/by-id 目录并找到指向所需设备的目录可能是最简单的。

于 2014-11-21T18:35:51.210 回答