实现的方法比较老土,但是是管用的。首先在程序开启一个线程周期性循环读取/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);
}
}