前言
Linux系统中,C语言监测U盘是否连接。
一、代码
使用到udev库,编译的时候需要链接udev(-ludev) , 代码如下:
#include <stdio.h>
#include <libudev.h>
#include <semaphore.h>
#include <unistd.h>
/* 参数定义 */
typedef struct
{
int UsbConnectState;
char UsbPath[TOOL_USB_PATH_MAX_LEN];
} UI_TOOL_USB_CHECK_T;
/* 全局变量 */
extern pthread_mutex_t mutex;
extern sem_t SemUsbCheck;
UI_TOOL_USB_CHECK_T ToolUsbCheckPara;
/* 检测usb设备 */
int UsbCheck(void)
{
/* 初始化udev */
struct udev *udev = udev_new();
if(!udev)
{
printf("Failed to initialize libudev.\n");
return -1;
}
/* 创建monitor */
struct udev_monitor *monitor = udev_monitor_new_from_netlink(udev, "udev");
if (!monitor)
{
printf("Failed to create udev monitor.\n");
udev_unref(udev);
return -1;
}
/* 监听U盘的事件 */
udev_monitor_filter_add_match_subsystem_devtype(monitor, "block", "disk");
udev_monitor_enable_receiving(monitor);
/* 循环监听事件 */
while (1)
{
struct udev_device *device = udev_monitor_receive_device(monitor);
if (device)
{
const char *action = udev_device_get_action(device);
const char *devnode = udev_device_get_devnode(device);
if (action && devnode)
{
int sta = 0;
char path[TOOL_USB_PATH_MAX_LEN] = {0};
int path_id;
if(0 == strcmp(action, "add"))
{
sta = 1;
/* 找出U盘路径 */
for(path_id = 0; path_id < 6; path_id++)
{
sprintf(path, "%s%d", devnode, path_id);
/* 判断路径是否存在 */
if(access(path, F_OK) == 0)
{
break;
}
}
if(path_id >= 6)
{
memset(path, 0, sizeof(path));
}
}
else if(0 == strcmp(action, "remove"))
{
sta = 0;
}
/* 加锁赋值 */
pthread_mutex_lock(&mutex);
ToolUsbCheckPara.UsbConnectState = sta;
sprintf(ToolUsbCheckPara.UsbPath, "%s", path);
pthread_mutex_unlock(&mutex);
/* 释放信号量 */
sem_post(&SemUsbCheck);
}
udev_device_unref(device);
}
sleep(1);
}
udev_monitor_unref(monitor);
udev_unref(udev);
return 0;
}