【问题标题】:ioctl and hdreg to get information on harddrivesioctl 和 hgreg 获取有关硬盘驱动器的信息
【发布时间】:2013-12-15 23:03:40
【问题描述】:

我想从硬盘驱动器获取基本信息并将其打印出来。最重要的是物理扇区大小正确。

在过去的几个小时里,我一直在与ioctl 斗争,以得到我想要的东西,但我想不通。

我以前从未使用过ioctl,而且我似乎无法找到一个简单的解释来说明你到底要做什么。

反正我的代码是这样的

int main () {
    FILE *driveptr;
    int sectorsize;
    struct hd_driveid hd;

    driveptr=fopen("/dev/sda","r");

    if (ioctl(driveptr,HDIO_GET_IDENTITY, &hd)!=0) { 
        printf("Hard disk model: %s\n",hd.model); 
        printf("Serial number: %s\n",hd.serial_no); 
        printf("Sector size: %i\n",hd.sector_bytes);
        sectorsize=hd.sector_bytes;
    } else { 
        printf("Error fetching device data.\n");
    }
}

在编译器中它会抛出这些警告,它会编译但打印时字符串是空的。

gcc -o test source.c
source.c: In function ‘main’:
source.c:67:9: warning: passing argument 1 of ‘ioctl’ makes integer from pointer without a cast [enabled by default]
/usr/include/x86_64-linux-gnu/sys/ioctl.h:42:12: note: expected ‘int’ but argument is of type ‘struct FILE *’

我希望有人可以向我解释出了什么问题!

【问题讨论】:

  • 现在硬盘不是经常谎报扇区大小吗?

标签: c disk ioctl sector


【解决方案1】:

代替

if (ioctl(driveptr,HDIO_GET_IDENTITY, &hd)!=0) { 

你可能想要

if (ioctl(fileno(driveptr),HDIO_GET_IDENTITY, &hd)!= -1) { 
          ^^^^^^^        ^                           ^^

因为ioctl的第一个参数需要是整数文件描述符而不是FILE *

fileno() 会给你一个来自FILE * 的整数 fd。

还要注意ioctl 在出错时返回 -1 并设置 errno。

阅读您正在使用的函数的手册页可能比发布到 StackOverflow 更快。

参见ioctl、fileno 的手册页。

【讨论】:

  • 谢谢!简短的问题,您知道这是“真正的”物理扇区大小还是逻辑扇区大小。我在网上看到使用 (ioctl(fileno(driveptr),BLKSSZGET, &sectorsize) 是最准确的方法。但它会向我抛出 60k 之类的数字。
  • 您还可以将 FILE* 变量替换为 int(文件描述符)并调用 open("/dev/sda", O_RDONLY) 而不是 fopen("/dev/sda", "r ”)。这样,您不必调用 fileno() 来将流转换为文件描述符。
猜你喜欢
  • 2014-01-11
  • 2012-08-07
  • 2019-07-04
  • 2012-05-04
  • 2018-01-26
  • 2019-09-13
  • 2021-04-21
  • 2010-09-18
相关资源
最近更新 更多