【问题标题】:How do I loop mount programmatically?如何以编程方式循环挂载?
【发布时间】:2012-07-02 22:54:53
【问题描述】:

我最近写了一个guide on how to mount partitions from image files on Raspberry Pi.SE。说明比较复杂,我有一点时间,所以想用a C program替换它们。我已经成功列出了图像的分区并计算到了适当的偏移量。

在原始指令中,我们需要运行

$ sudo mount -o loop,offset=80740352 debian6-19-04-2012.img /mnt

我现在需要在代码中执行此操作。我找到了mount 函数和libmount in util-linux

我现在在 util-linux 中找到了loopdev.c。有没有一种简单的方法来创建循环设备,还是我必须从这段代码中学习并使用 ioctl?

【问题讨论】:

  • 目前最简单的方法是从您的代码中调用mount(使用systemexec* 变体)。
  • 为什么不写shell脚本?
  • @iblue 我手头有一些时间......我也对 C 比 Bash 更有信心。 Git 最初是用 shell 脚本编写的,然后被移植了,我想我(愚蠢地?)错过了一步。
  • 您可以从 C 中分叉并执行 mount 命令,跳过 shell。看起来会很容易。您的 argv 将有几个固定字符串、一个用户提供的图像文件名和一个 sprintf(..., "loop,offset=%llu", offset)
  • @FaheemMitha 不,如果您查看我在Github 上的进度,您可以看到我正在计算偏移量。创建循环设备是个问题。

标签: mount c


【解决方案1】:

以下函数将循环设备device 绑定到file offset。成功返回 0,否则返回 1。

int loopdev_setup_device(const char * file, uint64_t offset, const char * device) {
  int file_fd = open(file, O_RDWR);
  int device_fd = -1; 

  struct loop_info64 info;

  if(file_fd < 0) {
    fprintf(stderr, "Failed to open backing file (%s).\n", file);
    goto error;
  }

  if((device_fd = open(device, O_RDWR)) < 0) {
    fprintf(stderr, "Failed to open device (%s).\n", device);
    goto error;
  }

  if(ioctl(device_fd, LOOP_SET_FD, file_fd) < 0) {
    fprintf(stderr, "Failed to set fd.\n");
    goto error;
  }

  close(file_fd);
  file_fd = -1; 

  memset(&info, 0, sizeof(struct loop_info64)); /* Is this necessary? */
  info.lo_offset = offset;
  /* info.lo_sizelimit = 0 => max avilable */
  /* info.lo_encrypt_type = 0 => none */

  if(ioctl(device_fd, LOOP_SET_STATUS64, &info)) {
    fprintf(stderr, "Failed to set info.\n");
    goto error;
  }

  close(device_fd);
  device_fd = -1; 

  return 0;

  error:
    if(file_fd >= 0) {
      close(file_fd);
    }   
    if(device_fd >= 0) {
      ioctl(device_fd, LOOP_CLR_FD, 0); 
      close(device_fd);
    }   
    return 1;
}

参考文献

  1. linux/loop.h
  2. piimg

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 2021-06-17
    • 2015-02-09
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    相关资源
    最近更新 更多