How to get disk name programmatically in Linux(Like "/dev/sda" or "/dev/sdb")?

2.6k Views Asked by At

I am trying out to find information related to Disk and partitions. Following are my code. But problem is that, I am passing disk name through command line by querying disk name from "/proc/partitions". Is there any api which can give me disk name as well.

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <blkid/blkid.h>

int main (int argc, char *argv[])
{
 blkid_probe pr;
 blkid_partlist ls;
 int nparts, i;

 pr = blkid_new_probe_from_filename(argv[1]);
 if (!pr)
 err(2, "faild to open device %s", argv[1]);

 ls = blkid_probe_get_partitions(pr);
 nparts = blkid_partlist_numof_partitions(ls);

for (i = 0; i < nparts; i++)
{
blkid_partition par = blkid_partlist_get_partition(ls, i);
printf("PartNo = %d\npart_start = %llu\npart_size =  %llu\npart_type = 0x%x\n",
blkid_partition_get_partno(par),
blkid_partition_get_start(par),
blkid_partition_get_size(par),
blkid_partition_get_type(par));
}

blkid_free_probe(pr);
return 0;

}
3

There are 3 best solutions below

0
On BEST ANSWER

One of the ways i have used is to parse info out of lshw :

lshw -class disk |grep "logical name"

another way is to check the ls /sys/block/sd*

0
On

You may do that by using libudev APIs to register to the "block" subsystem and parse through the list of block devices and get the path corresponding to the block device. Below is the snippet

struct udev_list_entry *devices;
struct udev_enumerate *enumerate;


enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "block");
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(dev_list_entry, devices) {
        char *path;
        path = udev_device_get_devnode(dev));
}
udev_enumerate_unref(enumerate);
0
On

There are a few ways to interpret your question.

Maybe you want to parse the output of the findmnt -Ar command. That provides all the currently mounted filesystems on the system in a safe parseable format.

But if you're looking for disk devices, that's a bit trickier. There are a lot of things on a Linux system that could potentially be disk devices, but are not actually being used as disks at the moment.

You might want to find all the /dev/sd* devices in the /dev directory like mch recommended, but that will not cover all possible devices. For example, my Linode has root mounted on /dev/xvda.

I ran an strace on the findmnt command, and found it just looks at /proc/filesystems (I think just to learn some magic numbers), /usr/lib/locale/locale-archive (maybe for some output formatting info, I don't know) and then /proc/self/mountinfo (with the actual information to read about the currently mounted filesystems). If you want to learn the info straight from the kernel, that's the way to do it.