#include
#include <libudev.h>
int main() {
struct udev *udev;
struct udev_monitor *monitor;
struct udev_device *device;
// 创建udev上下文
udev = udev_new();
if (!udev) {
std::cerr << "Failed to create udev context" << std::endl;
return 1;
}
// 创建监视器并设置过滤条件为USB设备
monitor = udev_monitor_new_from_netlink(udev, "udev");
udev_monitor_filter_add_match_subsystem_devtype(monitor, "usb", NULL);
udev_monitor_enable_receiving(monitor);
std::cout << "Monitoring for USB events..." << std::endl;
while (true) {
// 等待设备事件
device = udev_monitor_receive_device(monitor);
if (device) {
const char *action = udev_device_get_action(device);
const char *vendor = udev_device_get_sysattr_value(device, "idVendor");
const char *product = udev_device_get_sysattr_value(device, "idProduct");
if (action && vendor && product) {
std::cout << "Action: " << action << ", Vendor: " << vendor << ", Product: " << product << std::endl;
}
udev_device_unref(device);
}
}
// Cleanup
udev_monitor_unref(monitor);
udev_unref(udev);
return 0;
}
这个程序使用 udev 监听 uevent 事件,并在 USB 设备插入或拔出时打印相关信息。请注意,你需要在编译时链接 libudev 库,可以使用 -ludev 标志。
在运行此程序时,它将持续监听 USB 事件,当有 USB 设备插入或拔出时,将输出相应的信息。