在Linux中确定扇区大小的便携式方法

3

我想用C语言编写一个小程序,可以确定硬盘的扇区大小。我想读取位于/sys/block/sd[X]/queue/hw_sector_size的文件,在CentOS 6/7中已经成功实现。

但是,在CentOS 5.11中测试时,文件hw_sector_size丢失了,我只找到了max_hw_sectors_kbmax_sectors_kb

因此,我想知道如何在CentOS 5中(使用API)确定扇区大小,或者是否有更好的方法来实现。谢谢。


可能是Linux中未挂载的块设备信息的重复问题。 - jww
1个回答

10
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, &sect_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

好了,我们找到了一个似乎有用的ioctlBLKSSZGET。搜索BLKSSZGET,我们发现这个stackoverflow问题,其中在评论中包含以下信息:

供参考:BLKSSZGET = 逻辑块大小,BLKBSZGET = 物理块大小,BLKGETSIZE64 = 设备大小(以字节为单位),BLKGETSIZE = 设备大小/512。至少如果fs.h中的注释和我的实验是可信的。- Edward Falk Jul 10 '12 at 19:33


1
这真是太神奇了!非常感谢,Larsks! - vesontio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接