总体规划:
使用netlink接口向内核注册hotplug事件通知,获取事件通知后进行相关动作如(Action==add)挂载或(action==remove)卸载,使用Socket IPC机制向需要响应USB热拔插事件的应用程序报告。
功能包括:
1、获取usb卷标
2、挂载、卸载usb
3、动态监测usb热拔插事件
4、使用socket向应用程序报告热拔插事件
函数接口说明:
int reportToIplayer(USBEvent event,const char *servername);
向应用程序IPlayer报告热拔插事件
void check();
程序启动开始先检查当前u盘状态(空或者已存在)
int getDevPath(const char *buf,char *path,int size);
从热拔插事件的Diagram消息即buf中获得usb的设备路径存放到path,size为path缓冲大小
int rm_dir(const char *path);
删除挂载时建立的空目录
int make_dir(const char *devPath,const char *dstPath);
挂载钱建立一个空目录dstPath,dstPath为挂载目录
int get_label(const char *dev,char *buf,int size);
获取u盘卷标
int recordDstPath(int no,const char *dstPath);
记录下挂载路径,便于rm_dir查询
int init_hotplug_sock(void);
向内核注册hotplug事件
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef struct USBEvent
{
int event;
char path[30];
}USBEvent;
int init_hotplug_sock(void)
{
struct sockaddr_nl snl;
const int buffersize = 16*1024*1024;
int retval;
memset(&snl,0x00,sizeof(struct sockaddr_nl));
snl.nl_family = AF_NETLINK;
snl.nl_pid = getpid();
snl.nl_groups = 1;
int hotplug_sock = socket(PF_NETLINK,SOCK_DGRAM,NETLINK_KOBJECT_UEVENT);
if(hotplug_sock == 1)
{
printf("error get socket:%s",strerror(errno));
return -1;
}
/* set receive buffersize */
setsockopt(hotplug_sock,SOL_SOCKET,SO_RCVBUFFORCE,&buffersize,sizeof(buffersize));
retval = bind(hotplug_sock,(struct sockaddr *)&snl,sizeof(struct sockaddr_nl));
if(0>retval)
{
printf(&#