在一些跑linux 系统的平台上,比如故事机,会支持sdcard 热插拔的功能,也就是在sdcard 插入后,把sdcard mount到文件系统中,sdcard拔出后移除。上层应用要怎么知道这个事件呢,应用层可以注册监听uevent 事件即可,下面给出对应的实现。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <sys/mount.h>
#define EPOLL_FD_SIZE 3 //需要监听的fd个数
#define EPOLL_EVENT_SIZE 2
#define EPOLL_TIMEOUT 1000 //等待的超时时间,1000ms 也就是1秒
#ifndef KERNEL_UEVENT_LEN
#define KERNEL_UEVENT_LEN (4*1024)
#endif
typedef struct
{
int epoll_fd; //epoll 对应的fd
int uevent_fd; //热插拔节点的sock 句柄
pthread_t hotplug_thread; //对应的线程
int is_start; //线程是否已经创建
int is_running; //是否在while循环中运行
} hotplug_context_t;
static hotplug_context_t hotplug =