gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:27 26 4
gpt4 key购买 nike

我想用C写一个小程序,可以确定硬盘的扇区大小。我想读取位于 /sys/block/sd[X]/queue/hw_sector_size 的文件,它在 CentOS 6/7 中工作。

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

因此,我想知道如何确定(API)CentOS 5 中的扇区大小,或者是否有其他更好的方法来这样做。谢谢。

最佳答案

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 中查找 扇区大小代码,我们在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 开始,因为该文件名听起来很有前途。通过该文件查找我用来列出文件的相同正则表达式,我们发现 this :

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.cblkdev_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

我们开始了。有一个 BLKSSZGET ioctl 似乎很有用。搜索 BLKSSZGET 会将我们带到 this stackoverflow question ,其中在评论中包含以下信息:

For the record: BLKSSZGET = logical block size, BLKBSZGET = physical block size, BLKGETSIZE64 = device size in bytes, BLKGETSIZE = device size/512. At least if the comments in fs.h and my experiments can be trusted. – Edward Falk Jul 10 '12 at 19:33

关于c - 在 Linux 中确定扇区大小的便携方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com