确认创建的虚拟文件是否mount

本文介绍了一种通过ioctl系统调用和loop_info64结构体来检查Linux系统中loop设备是否已挂载的方法。通过比较loop设备上的文件名与目标文件名,可以确定特定的loop设备是否正用于挂载指定的映像文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过loop_info中字段去确认是否mount

/* Backwards compatibility version */
struct loop_info {
	int		   lo_number;		/* ioctl r/o */
	__kernel_old_dev_t lo_device; 		/* ioctl r/o */
	unsigned long	   lo_inode; 		/* ioctl r/o */
	__kernel_old_dev_t lo_rdevice; 		/* ioctl r/o */
	int		   lo_offset;
	int		   lo_encrypt_type;
	int		   lo_encrypt_key_size; 	/* ioctl w/o */
	int		   lo_flags;			/* ioctl r/o */
	char		   lo_name[LO_NAME_SIZE];
	unsigned char	   lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
	unsigned long	   lo_init[2];
	char		   reserved[4];
};

struct loop_info64 {
	__u64		   lo_device;			/* ioctl r/o */
	__u64		   lo_inode;			/* ioctl r/o */
	__u64		   lo_rdevice;			/* ioctl r/o */
	__u64		   lo_offset;
	__u64		   lo_sizelimit;/* bytes, 0 == max available */
	__u32		   lo_number;			/* ioctl r/o */
	__u32		   lo_encrypt_type;
	__u32		   lo_encrypt_key_size;		/* ioctl w/o */
	__u32		   lo_flags;			/* ioctl r/o */
	__u8		   lo_file_name[LO_NAME_SIZE];
	__u8		   lo_crypt_name[LO_NAME_SIZE];
	__u8		   lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
	__u64		   lo_init[2];
};
#include <fcntl.h>
#include <linux/loop.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
                       } while (0)

int main(int argc, char *argv[])
{
   int ret = -1;
   int fd = -1;
   int i = 0;
   long devnr;
   char loopname[4096];
   char test_name[]="/home/user/test.img";
   struct loop_info64 test = {0};

   for(i=0 ; i < 8; i++)
   {
        sprintf(loopname, "/dev/loop%d", i);
        fd = open(loopname, O_RDONLY);
        if(fd == -1){
               errExit("open: loopname");
        }
        ret = ioctl(fd, LOOP_GET_STATUS64, &test);
        close(fd);
        if(ret != 0)
        {
           errExit("ret");
        }
        if(strcmp(test.lo_file_name, test_name) == 0)
        {
             printf("lo_file_name:%s test_name:%s\n", test.lo_file_name, test_name);
             exit(EXIT_SUCCESS);
        }
   }
   exit(EXIT_SUCCESS);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值