我最近写了一个关于如何在Raspberry Pi.SE上从图像文件挂载分区的指南.说明相当复杂,我有一点时间,所以想用C程序替换它们.我已成功列出图像的分区并计算到适当的偏移量.
在原始说明中,我们需要运行
$ sudo mount -o loop,offset=80740352 debian6-19-04-2012.img /mnt
Run Code Online (Sandbox Code Playgroud)
我现在需要在代码中执行此操作.我在util-linux中找到了mount函数和libmount.
我现在在util-linux中找到了loopdev.c.有没有一种简单的方法来创建循环设备或我是否必须从这些代码中学习并使用ioctl?
Ale*_*ain 10
以下函数将循环设备绑定device到fileat 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;
}
Run Code Online (Sandbox Code Playgroud)