我想read()
从 SATA HDD做一个基本的/dev/sdd
。Awrite()
似乎工作。也可以在没有标志的情况read()
下工作。我读过,它必须与块大小对齐。所以我用它来获取块大小:write()
O_DIRECT
root$ blockdev --getsize /dev/sdd
488397168
root$ blockdev --getsize64 /dev/sdd
250059350016
root$ python -c "print 250059350016.0/488397168"
512.0
如您所见,我有根。硬盘通过 PCIe SATA 卡连接,并向lspci -vv
我显示它使用基本的 ahci ( drivers/ata/ahci.c
) 驱动程序。我在 64 位 Power Architecture 上使用 3.2.0 Linux 内核。
这是我的代码:
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main() {
int r;
char *buffer, *tmp_buffer;
// alloc more than necesarry to align the real buffer
tmp_buffer = malloc(2*512*sizeof(char));
long align = (unsigned long)tmp_buffer%512;
printf("tmp_buffer is at: %x \% 512 = %d\n",tmp_buffer,align);
buffer = tmp_buffer+(512-align);
printf("buffer is at: %x \% 512 = %d\n",buffer,(unsigned long)buffer%512);
memset(buffer,0,sizeof(512));
// OPEN
int fd = open("/dev/sdd",O_DIRECT | O_RDWR | O_SYNC);
if(fd!=3) printf("fd = %d\n",fd);
// READ
printf("try to read and then dump buffer:\n");
r = read(fd,buffer,sizeof(512));
if(r == -1) printf("Error: %s\n",strerror(errno));
else {
// DUMP BUFFER
int i;
for(i=0; i<sizeof(512); i++)
printf("%c",buffer[i]);
}
printf("\n");
return 0;
}
输出是:
tmp_buffer is at: 1cc80010 % 512 = 16
buffer is at: 1cc80200 % 512 = 0
try to read and then dump buffer:
Error: Invalid argument
编辑:我已经按照 Brett Hale 的回答更新了我的来源。不幸的是,我仍然得到错误。我找出块大小的方法可以吗?我做对了吗?
非常感谢您阅读,
费边