Block device information without mounting in Linux

后端 未结 2 1763
日久生厌
日久生厌 2021-01-13 03:01

I am trying to get some information (specifically block size) of block device in linux, in C++. Is it possible to get block size of a device without mounting it and possibly

相关标签:
2条回答
  • 2021-01-13 03:09

    You want to use ioctl, in particular BLKSSZGET.

    Quoting linux/fs.h:

    #define BLKSSZGET  _IO(0x12,104)/* get block device sector size */
    

    Untested example:

    #include <sys/ioctl.h>
    #include <linux/fs.h>
    
    int fd = open("/dev/sda");
    size_t blockSize;
    int rc = ioctl(fd, BLKSSZGET, &blockSize);
    
    0 讨论(0)
  • 2021-01-13 03:18

    I think the ioctl value should rather be unsigned long than size_t (the latest is more memory related), I would also initialize it to 0 (just in case BLKSSZGET returns unsigned int instead).

    #include <sys/ioctl.h>
    #include <linux/fs.h>
    
    int fd = open("/dev/sda");
    unsigned long blockSize = 0;
    int rc = ioctl(fd, BLKSSZGET, &blockSize);
    
    0 讨论(0)
提交回复
热议问题