How do I get the drive name programmatically in Linux (like "/ dev / sda" or "/ dev / sdb")?

I am trying to find disk and partition related information. Below is my code. But the problem is that I am passing the drive name through the command line, asking for the drive name from "/ proc / partition". Is there an api that can give me the drive name.

#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",

return 0;




source to share

3 answers

One of the ways I have used is to analyze information from lshw


lshw -class disk |grep "logical name"

Another way is to check ls /sys/block/sd*



There are several ways to interpret your question.

Perhaps you want to parse the command output findmnt -Ar

. This ensures all currently mounted file systems on the system are in a secure parsing format.

But if you're looking for disk drives, it's a little more complicated. There are many things in Linux that can potentially be disk devices, but they are not really used as disks at this time.

You might want to find all /dev/sd*

devices in a directory /dev

, such as those recommended by mch, but that won't cover every possible device. For example, my Linode has root set to /dev/xvda


I ran strace

in command findmnt

and found that it just looks at /proc/filesystems

(I think just to find out some magic numbers), /usr/lib/locale/locale-archive

(maybe for some output formatting info, t) and then /proc/self/mountinfo

(with actual information to read about currently mounted file systems). If you want information straight from the kernel, this is the way to do it.



You can do this by using the libudev APIs to register with the "block" subsystem and parse the list of device blocks and get the path corresponding to the block device. Below is a snippet

struct udev_list_entry *devices;
struct udev_enumerate *enumerate;

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




All Articles