如何以编程方式循环挂载? [英] How do I loop mount programmatically?
问题描述
我最近写了一篇关于如何从 Raspberry Pi.SE 上的图像文件挂载分区的指南.指令相当复杂,我有一点时间,所以想用一个C程序替换它们.我已成功列出图像的分区并计算出适当的偏移量.
I have recently written a guide on how to mount partitions from image files on Raspberry Pi.SE. The instructions are rather complicated and I have a bit of time, so want to replace them by a C program. I have successfully listed the partitions of the image and calculated to appropriate offsets.
在原始指令中,我们需要运行
In the original instructions, we needed to run
$ sudo mount -o loop,offset=80740352 debian6-19-04-2012.img /mnt
我现在需要在代码中执行此操作.我找到了 mount 函数和 util-linux 中的libmount.
I now need to do this in code. I have found the mount function and libmount in util-linux.
我现在找到了 loopdev.c在 util-linux 中.有没有一种简单的方法来创建循环设备,还是我必须从这段代码中学习并使用 ioctl?
I have now found loopdev.c in util-linux. Is there an easy way to create loop devices or do I have to learn from this code and use ioctl?
推荐答案
以下函数将循环设备device
绑定到offset
处的file
.成功返回 0,否则返回 1.
The following function binds the loop device device
to file
at offset
. It returns 0 on success, 1 otherwise.
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;
}
参考资料
这篇关于如何以编程方式循环挂载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!