Linux下通过程序实现自动挂载U盘

实现的方法比较老土,但是是管用的。首先在程序开启一个线程周期性循环读取/proc/partitions文件中的内容,该文件是系统的分区表,如果U盘插入的话会有一个新的设备出现,可以通过该文件读取设备名,注意一下这里U盘插入之后dev文件夹中会多出sdb和sdb1两个文件来,其中sdb表示的是一块硬盘,sdb1表示的是sdb硬盘的第一个分区,挂载的时候需要挂载sdb1而不是sdb,如果有多个分区的话就也可以挂载其他分区。下面是通过/proc/partitions文件进行挂载的简单测试程序:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <asm/types.h>

void main()
{
	int stat = 0;
	unsigned char buff[1024];
	unsigned char cmd[100];
	unsigned char disk[5];
	while(1)
	{
		if(stat == 0)
		{
			int fd = open("/proc/partitions",O_RDWR);
			if(fd > 0)
			{
				memset(buff,0,1024);
				read(fd,buff,1024);
				// printf("%s\r\n",buff);
				unsigned char *p = strstr(buff,"sd");
				if(p != NULL)
				{
					p = strstr(p + 3,"sd");
					if(p != NULL)
					{
						memcpy(disk,p,4); 
						disk[5] = 0;
						printf("%s\r\n",disk);
						stat = 1;
					}
				}
				close(fd);
			}
		}
		else if(stat == 1)
		{
			system("mkdir temp_dir");
			sprintf(cmd,"mount /dev/%s ./temp_dir",disk);
			printf("%s\r\n",cmd);  
			system(cmd);
			stat = 2;
		}
		else if(stat == 2)
		{
			system("ls ./temp_dir -al");
			int cfg_fd = open("./temp_dir/config",O_RDWR);
			if(cfg_fd > 0)
			{
				system("cat ./temp_dir/config");
				close(cfg_fd);
			}
			else
			{
				printf("no config file\r\n");
			}
			system("umount ./temp_dir");
			system("rmdir temp_dir");
			stat = 3;
		}
		else if(stat == 3)
		{
			int fd = open("/proc/partitions",O_RDWR);
			if(fd > 0)
			{
				memset(buff,0,1024);
				read(fd,buff,1024);
				// printf("%s\r\n",buff);
				unsigned char *p = strstr(buff,"sd");
				if(p == NULL)
				{
					stat = 0;
					printf("udisk ejected\r\n");
				}
				close(fd);
			}
		}
		usleep(1000000);
	}
}





  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值