Search code examples
clinuxfilesystemsblock-deviceblkid

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


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;

}

Solution

  • 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*