我想用C语言编写一个小程序,可以确定硬盘的扇区大小。我想读取位于/sys/block/sd[X]/queue/hw_sector_size
的文件,在CentOS 6/7中已经成功实现。
但是,在CentOS 5.11中测试时,文件hw_sector_size
丢失了,我只找到了max_hw_sectors_kb
和max_sectors_kb
。
因此,我想知道如何在CentOS 5中(使用API)确定扇区大小,或者是否有更好的方法来实现。谢谢。
我想用C语言编写一个小程序,可以确定硬盘的扇区大小。我想读取位于/sys/block/sd[X]/queue/hw_sector_size
的文件,在CentOS 6/7中已经成功实现。
但是,在CentOS 5.11中测试时,文件hw_sector_size
丢失了,我只找到了max_hw_sectors_kb
和max_sectors_kb
。
因此,我想知道如何在CentOS 5中(使用API)确定扇区大小,或者是否有更好的方法来实现。谢谢。
fdisk
实用程序显示此信息(即使在 CentOS 5 上运行的内核版本早于 2.6.x),因此这似乎是寻找答案的一个可能地方。幸运的是,我们生活在美妙的开源世界中,所以只需要进行一点调查。fdisk
程序由util-linux包提供,因此我们需要先安装它。
扇区大小在fdisk
的输出中显示如下:
Disk /dev/sda: 477 GiB, 512110190592 bytes, 1000215216 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
如果我们在util-linux代码中查找Sector size
,我们可以在disk-utils/fdisk-list.c中找到它:
fdisk_info(cxt, _("Sector size (logical/physical): %lu bytes / %lu bytes"),
fdisk_get_sector_size(cxt),
fdisk_get_physector_size(cxt));
看起来我们需要找到fdisk_get_sector_size
,它在libfdisk/src/context.c中定义:
unsigned long fdisk_get_sector_size(struct fdisk_context *cxt)
{
assert(cxt);
return cxt->sector_size;
}
嗯,那并不是特别有帮助。我们需要找出 cxt->sector_size
设置的位置:
$ grep -lri 'cxt->sector_size.*=' | grep -v tests
libfdisk/src/alignment.c
libfdisk/src/context.c
libfdisk/src/dos.c
libfdisk/src/gpt.c
libfdisk/src/utils.c
我将从alignment.c
开始,因为这个文件名听起来很有前途。 在该文件中查找与我用于列出文件的相同的正则表达式,我们发现这个:
cxt->sector_size = get_sector_size(cxt->dev_fd);
这导致了:
static unsigned long get_sector_size(int fd)
{
int sect_sz;
if (!blkdev_get_sector_size(fd, §_sz))
return (unsigned long) sect_sz;
return DEFAULT_SECTOR_SIZE;
}
这反过来又引导我去看lib/blkdev.c中的blkdev_get_sector_size
定义:
#ifdef BLKSSZGET
int blkdev_get_sector_size(int fd, int *sector_size)
{
if (ioctl(fd, BLKSSZGET, sector_size) >= 0)
return 0;
return -1;
}
#else
int blkdev_get_sector_size(int fd __attribute__((__unused__)), int *sector_size)
{
*sector_size = DEFAULT_SECTOR_SIZE;
return 0;
}
#endif
好了,我们找到了一个似乎有用的ioctl
: BLKSSZGET
。搜索BLKSSZGET
,我们发现这个stackoverflow问题,其中在评论中包含以下信息:
供参考:BLKSSZGET = 逻辑块大小,BLKBSZGET = 物理块大小,BLKGETSIZE64 = 设备大小(以字节为单位),BLKGETSIZE = 设备大小/512。至少如果fs.h中的注释和我的实验是可信的。- Edward Falk Jul 10 '12 at 19:33