【问题标题】:How do I read/write a block device?如何读/写块设备?
【发布时间】:2014-10-24 02:44:42
【问题描述】:

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

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);
}

【问题讨论】:

  • 您的~/file 有多大?对小文件执行losetup 可能对系统工具无用或不可见。
  • @ymonad 一个句子,大约 40bytes。我尝试使用`dd if=/dev/zero of=~/file2 count=10K`创建一个新文件,然后用vi编辑它。它似乎工作。它只是因为我有一个小文件而忽略它还是在它
  • 在我的环境中losetup 给我一个大文件警告:“警告:文件不适合 512 字节的扇区;文件末尾将被忽略” i> ,对于小文件:“警告:文件小于 512 字节;循环设备可能对系统工具无用或不可见。” .所以后者可能是正确的。
  • 此警告似乎是从util-linux 2.22 版添加的。 github.com/karelzak/util-linux/commit/…

标签: c linux block-device


【解决方案1】:

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

当使用losetup 将文件映射到/dev/loopX 时, 对于小于 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 版在this commit 中添加此警告

【讨论】:

  • 这绝不是一个答案!它是如何获得投票的?什么是实际修复?
  • @Kevin 实际的解决方法是使用大小为 512 倍数的文件。也许问题的标题不符合您的需要。
  • 解决这个问题的语法是什么?那将是一个实际的答案)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多