8

如何读/写块设备?我听说我像普通文件一样读/写,所以我设置了一个循环设备

sudo losetup /dev/loop4 ~/file

然后我在文件上运行应用程序,然后在循环设备上运行

sudo ./a.out file
sudo ./a.out /dev/loop4

该文件完美执行。循环设备读取 0 个字节。在这两种情况下,我得到 FP==3 和 off==0。文件正确获取字符串长度并打印字符串,而循环让我得到 0 并且什么也不打印

如何读/写块设备?

#include <fcntl.h>
#include <cstdio>
#include <unistd.h>

int main(int argc, char *argv[]) {
    char str[1000];

    if(argc<2){
        printf("Error args\n");
        return 0;
    }

    int fp = open(argv[1], O_RDONLY);
    printf("FP=%d\n", fp);
    if(fp<=0) {
        perror("Error opening file");
        return(-1);
    }
    off_t off = lseek(fp, 0, SEEK_SET);
    ssize_t len = read(fp, str, sizeof str);
    str[len]=0;
    printf("%d, %d=%s\n", len, static_cast<int>(off), str);

    close(fp);
}
4

1 回答 1

6

losetup似乎在 512 字节扇区中映射文件。如果文件大小不是 512 的倍数,则其余部分将被截断。

将文件映射到/dev/loopXwith 时losetup,对于小于 512 字节的文件,它会给我们以下警告:

Warning: file is smaller than 512 bytes;
 the loop device may be useless or invisible for system tools.

对于大小不能除以 512 的文件:

Warning: file does not fit into a 512-byte sector;
 the end of the file will be ignored

util-linux自2.22 版以来在此提交中添加了此警告

于 2014-10-24T09:01:21.560 回答