【问题标题】:How to validate data read from LBA is correct?如何验证从 LBA 读取的数据是否正确?
【发布时间】:2012-07-06 18:55:03
【问题描述】:

我有这个程序从 LBA(逻辑块地址)读取数据,但每次我提供的 LBA 编号,它都会给出相同的输出。

如何验证?

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <linux/fs.h>
//#include "common.h"

typedef unsigned long long int var64;


int getSectorSize(int handle)
{
        int sectorSize = 0;

        //get the physical sector size of the disk
        if (ioctl(handle, BLKSSZGET, &sectorSize)) {

                printf("getSectorSize: Reading physical sector size failed.\n");

                sectorSize = 512;
        }

        return sectorSize;
}



var64 readLBA(int handle, var64 lba, void* buf, var64 bytes)
{
        int ret = 0;
        int sectorSize = getSectorSize(handle);
        var64 offset = lba * sectorSize;

        printf("readFromLBA: entered.\n");

        lseek64(handle, offset, SEEK_SET);
        ret = read(handle, buf, bytes);
        if(ret != bytes) {

              printf("read LBA: read failed.\n");

                return -1;
        }

        printf("read LBA: retval: %lld.\n", ret);
        return ret;
}

int main()
{
  int sectorSize, fd;
  char buff[100];
  printf("Calling getSectorSize\n");

  fd = open("/dev/sda1", O_RDONLY);

  if(fd == -1)
  {
    printf("open /dev/sda1 failed");
    exit(1);
  }
  sectorSize = getSectorSize(fd);
  printf("Sector size = %u\n", sectorSize);
  memset(buff, 0, sizeof(buff)); 
  readLBA(fd, 1, buff, 2); // if i put the 2nd arg as -12378 gives same answer
}

这是输出:

sles10-sp3:~ # gcc getSectorSizeMain.c
getSectorSizeMain.c: In function ‘main’:
getSectorSizeMain.c:75: warning: incompatible implicit declaration of built-in function ‘memset’
sles10-sp3:~ # ./a.out
Calling getSectorSize
Sector size = 512
read LBA: entered.
read LBA: retval: 8589934594. // This is always constant, how to validate? If i tell to read an invalid LBA number like -123456 the answer remains same. How to validate?

【问题讨论】:

    标签: c linux diskspace hard-drive


    【解决方案1】:

    retval 不包含您感兴趣的数据,但是 read() 的字节数已存储到您的缓冲区中,因此很自然它总是包含相同的值。但是在您的测试输出中,您尝试使用“%lld”(long long int)打印它,即使它只是一个普通的 int,所以 printf 会将它的值与它在堆栈上找到的任何东西结合起来(注意 8589934594= =0x200000002 - 最后一个数字是你的值,第一个可能是垃圾)。

    您要检查/使用/无论在数组 buff 中的数据。

    【讨论】:

    • 谢谢,它在以十六进制(buff)打印时打印一些有意义的东西,但是如果我将 number_of_bytes 读取(第三个参数)从 LBA 读取到 2 或 12,为什么 buff 参数不会增加?我的意思是提到第 3 个参数,因为 13 应该从 LBA 读取 13 个参数,但它以十六进制打印相同数量的数字(数据读取:bfb31868 在 13 的情况下)数据读取:bfb61098 在 3 的情况下。
    • @kingsmasher1:您必须自己指定要打印的字节数 - printf() 说明符都假定特定类型 大小以打印下一个值(例如 %x 将获取接下来的 4 个字节并将它们解释为 int 值)。
    • 你的意思是打印成 buff[0],buff[1],像这样?我刚刚打印为:printf("%x", buff); 它会打印类似 bfb61098 的内容,但是如果我打印 buff[0], buff[1] 它会像这样打印 1, 0。我猜两者都不正确。
    • 是的,我的意思是单独打印每个元素(如printf("%x", buff[0]); 等 - 这应该为您提供每个缓冲区元素的十六进制值。(但我不确定我会期望哪些值那里)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2013-06-11
    • 2016-10-21
    • 2023-03-17
    相关资源
    最近更新 更多