6 c++ unix linux filesystems posix
我正在研究高性能I/O程序,我正在尝试找到用C++确定设备磁盘块的物理(而非逻辑)字节大小的最佳方法.到目前为止,我的研究使我得到以下代码片段:
#include <iostream>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char ** argv)
{
// file information including block size of the device
struct stat info;
// device to get block size from
char * device = "/mnt/hdb1";
if (stat(device, &info))
{
printf("stat() error");
strerror(errno);
exit(1);
}
printf("Prefered block size for '%s' is %i byte\n", device, info.st_blksize);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
手册页中有以下内容st_blksize:
st_blksize字段为高效的文件系统I/O提供"首选"块大小.(以较小的块写入文件可能会导致读取 - 修改 - 重写效率低下.)
,但它没有提到st_blksize是逻辑块还是物理磁盘块大小.
所以,是st_blksize所述物理磁盘块大小,以及如果是的话,则是检测物理盘块大小此最POSIX OS可移植的方法.
我写了一个答案,虽然有希望对块设备无法正常工作.
没有用于获取设备的基本物理块大小的POSIX机制,您将不得不诉诸ioctl,这取决于平台.
对于Linux来说 ioctl(fd, BLKPBSZGET, &block_size)
对于Solaris,有dkio接口,允许您获取物理块大小.
dk_minfo_ext media_info;
if (-1 != ioctl(fd, DKIOMEDIAINFOEXT, &media_info))
block_size = media_info.dki_pbsize;
Run Code Online (Sandbox Code Playgroud)
对于Mac OS X,它是ioctl(fd, DKIOCGETPHYSICALBLOCKSIZE, &block_size).
对于FreeBSD,它应该是iotcl(fd, DIOCGSECTORSIZE, &block_size).