使用 sys/mount.h 挂载 ISO

2023-12-23

我正在尝试在 Linux 中的 C++ 程序中挂载 ISO 文件

我知道 linux 命令可以实现此目的,即 mount -o Loop ~/Test.iso /mnt/myISO

但是 mount(2) 手册页声明了以下安装原型:

int mount(const char *source, const char *target,
const char *filesystemtype, unsigned long mountflags,
const void *data);

我如何在这里指定循环选项?

--

另外,在 Linux 编程中,使用 C++ 的系统 shell 调用来实现此类任务,一般来说是一种好的(/可接受的)做法吗?


小例子

#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,"");
}

更新: 卸载后,您需要自由循环:

device_fd = open("/dev/loop0", O_RDWR);
...
if (ioctl(device_fd, LOOP_CLR_FD, 0) < 0) {
    perror("ioctl LOOP_CLR_FD failed");
    return 1;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 sys/mount.h 挂载 ISO 的相关文章

随机推荐