clinuxsuperblock

How do you find where the end of a partition ends on a Linux drive?


In one of my classes our assignment is to find and print some values in the first superblock and then compare those values against all other superblocks in the power of 3, 5 and 7 until the end of the partition.

So for example, you compare superblock0 with superblock1, 0 and 3, 0 and 5, 0 and 7, 0 and 9 and so on.

My code to output the values in a superblock works, and I have an algorithm in mind that will get all powers of 3, 5 and 7 but I'm not sure how to detect the end of the partition.

And how to loop through all superblocks with those powers until the end or what the break case would be.

Below is my code to access the first superblock.

int fd;
super_block_t s;

if((fd = open(DEVICE, O_RDONLY)) < 0){ //check if disk can be read
    perror(DEVICE);
    exit(1);
} 

//read superblock
lseek(fd, OFFSET, SEEK_SET);
read(fd, &s, sizeof(s));
close(fd);

Solution

  • You can either try to seek there and see if you get a EINVAL, or you can use the BLKGETSIZE64 ioctl to fetch the size of the block device:

    #include <linux/fs.h>
    #include <stdint.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <sys/ioctl.h>
    
    void main(int argc, char** argv) {
      int fd = open(argv[1], O_RDONLY);
      uint64_t size;
      ioctl(fd, BLKGETSIZE64, &size);
      printf("Size in bytes: %llu\n", size);
    }