小例子
#include <sys/mount.h>
#include <linux/loop.h>
#include <fcntl.h>
int main()
{
int file_fd, device_fd;
file_fd = open("./TVM_TOMI1.iso", O_RDWR);
if (file_fd < -1) {
perror("open backing file failed");
return 1;
}
device_fd = open("/dev/loop0", O_RDWR);
if (device_fd < -1) {
perror("open loop device failed");
close(file_fd);
return 1;
}
if (ioctl(device_fd, LOOP_SET_FD, file_fd) < 0) {
perror("ioctl LOOP_SET_FD failed");
close(file_fd);
close(device_fd);
return 1;
}
close(file_fd);
close(device_fd);
mount("/dev/loop0","/mnt/iso","iso9660",MS_RDONLY,"");
}
upd:卸载后你需要自由循环:
device_fd = open("/dev/loop0", O_RDWR);
...
if (ioctl(device_fd, LOOP_CLR_FD, 0) < 0) {
perror("ioctl LOOP_CLR_FD failed");
return 1;
}