文章目录
- 获取挂载路径
- 监控U盘热拔插事件
- 添libudev加库
获取挂载路径
#include <stdio.h>
#include <libudev.h>
#include <string.h>int main() {struct udev *udev;struct udev_enumerate *enumerate;struct udev_list_entry *devices, *entry;// 创建udev上下文和设备枚举器udev = udev_new();if (!udev) {printf("Failed to create udev context\n");return 1;}enumerate = udev_enumerate_new(udev);if (!enumerate) {printf("Failed to create udev enumerate\n");udev_unref(udev);return 1;}// 添加匹配过滤器以选择块设备(U盘)udev_enumerate_add_match_subsystem(enumerate, "block");udev_enumerate_scan_devices(enumerate);devices = udev_enumerate_get_list_entry(enumerate);// 遍历设备列表并获取设备信息udev_list_entry_foreach(entry, devices) {const char *sys_path = udev_list_entry_get_name(entry);struct udev_device *dev = udev_device_new_from_syspath(udev, sys_path);const char *devnode = udev_device_get_devnode(dev);printf("Device node path: %s\n", udev_device_get_devnode(dev));
#if 0// 检查设备是否是U盘,可以根据需求添加其他判断条件if (udev_device_get_devtype(dev) && strcmp(udev_device_get_devtype(dev), "disk") == 0) {printf("U盘挂载路径:%s\n", devnode);}
#endifudev_device_unref(dev);}// 清理资源udev_enumerate_unref(enumerate);udev_unref(udev);return 0;
}
编译指令
gcc your_code.c -o your_executable -ludev
监控U盘热拔插事件
#include <stdio.h>
#include <libudev.h>
#include <string.h>int main() {struct udev *udev;struct udev_enumerate *enumerate;struct udev_list_entry *devices, *entry;// 创建udev上下文和设备枚举器udev = udev_new();if (!udev) {printf("Failed to create udev context\n");return 1;}struct udev_monitor *mon = udev_monitor_new_from_netlink(udev, "udev");
int fd = udev_monitor_get_fd(mon);udev_monitor_filter_add_match_subsystem_devtype(mon, "block", NULL);
udev_monitor_enable_receiving(mon);while (1) {fd_set fds;FD_ZERO(&fds);FD_SET(fd, &fds);// 使用select函数等待设备事件if (select(fd+1, &fds, NULL, NULL, NULL) > 0) {if (FD_ISSET(fd, &fds)) {struct udev_device *dev = udev_monitor_receive_device(mon);if (dev) {const char *action = udev_device_get_action(dev);// 判断事件类型,处理U盘插入和移除事件if (strcmp(action, "add") == 0) {printf("U盘插入\n");} else if (strcmp(action, "remove") == 0) {printf("U盘移除\n");}udev_device_unref(dev);}}}
}// 清理资源udev_enumerate_unref(enumerate);udev_unref(udev);return 0;
}
添libudev加库
sudo apt-get install libudev-dev