Home > database >  How to detect block devices on Linux?
How to detect block devices on Linux?

Time:06-16

With C on Linux, how does one detect block devices? Right now, I'm using this code:

for (const auto &entry : std::filesystem::directory_iterator("/dev/"))
{
    std::string name = entry.path().filename().string();
    if (name.find("sd") == 0 || name.find("nvme") == 0 || name.find("hd") == 0 || name.find("vd") == 0 || name.find("xvd") == 0)
    {
        std::cout << "Found device: " << entry.path() << std::endl;
    }
}

Which works well enough in practice, but almost certainly isn't the way it's "supposed to be done". And it isn't perfect either, as it misses losetup devices because I didn't include "loop", it also misses Network Block Devices because I didn't include "nbd".

CodePudding user response:

std::filesystem::directory_entry has an is_block_file() method for this exact purpose:

Checks whether the pointed-to object is a block device.

For example:

for (const auto &entry : std::filesystem::directory_iterator("/dev/"))
{
    if (entry.is_block_file())
    {
        std::cout << "Found device: " << entry.path() << std::endl;
    }
}

CodePudding user response:

Something like this should do it (untested, no error checking for brevity):

const char *maybe_block_device = ...;
struct stat st;
stat (maybe_block_device, &st);
bool is_block_device = S_ISBLK (st.st_mode);

Where S_ISBLK is a 'helper' macro.

Documentation here and here.

  • Related