I want to write a small program in C which can determine the sector size of a hard disk. I wanted to read the file located in /sys/block/sd[X]/queue/hw_sector_size
, and it worked in CentOS 6/7.
However when I tested in CentOS 5.11, the file hw_sector_size
is missing, and I have only found max_hw_sectors_kb
and max_sectors_kb
.
Thus, I'd like to know how can I determine (APIs) the sector size in CentOS 5, or is there an other better way to do so. Thanks.
The
fdisk
utility displays this information (and runs successfully on kernels older even than than the 2.6.x vintage on CentOS 5), so that seems a likely place to look for an answer. Fortunately, we're living in the wonderful world of open source, so all it requires is a little investigation.The
fdisk
program is provided by the util-linux package, so we need that first.The sector size is displayed in the output of
fdisk
like this:If we look for
Sector size
in the util-linux code, we find it in disk-utils/fdisk-list.c:So, it looks like we need to find
fdisk_get_sector_size
, which is defined in libfdisk/src/context.c:Well, that wasn't super helpful. We need to find out where
cxt->sector_size
is set:I'm going to start with
alignment.c
, since that filename sounds promising. Looking through that file for the same regex I used to list the files, we find this:Which leads me to:
Which in turn leads me to the definition of
blkdev_get_sector_size
in lib/blkdev.c:And there we go. There is a
BLKSSZGET
ioctl
that seems useful. A search forBLKSSZGET
leads us to this stackoverflow question, which includes the following information in a comment: