[英]How do I loop mount programmatically?
我最近寫了一篇關於如何在Raspberry Pi.SE上從圖像文件掛載分區的指南 。 說明相當復雜,我有一點時間,所以想用C程序替換它們。 我已成功列出圖像的分區並計算到適當的偏移量。
在原始說明中,我們需要運行
$ sudo mount -o loop,offset=80740352 debian6-19-04-2012.img /mnt
我現在需要在代碼中執行此操作。 我在util-linux中找到了mount函數和libmount 。
我現在在util-linux中找到了loopdev.c 。 有沒有一種簡單的方法來創建循環設備或我是否必須從這些代碼中學習並使用ioctl?
以下函數將循環設備device
綁定到offset
file
。 成功時返回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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.