Linux检测U盘热插拔,插入拔出会发送信号,父类的槽需要自己实现接收逻辑。
USBWatcher.h
#include <libudev.h> #include <QObject> class QSocketNotifier; class USBWatcher : public QObject { Q_OBJECT public: explicit USBWatcher(QObject *parent = nullptr) ; void CheckConnectedUSBDevices(); //程序启动首次监测 U盘是否插入 signals: void usbDeviceConnected(); void usbDeviceDisconnected(); private slots: void handleDeviceChange(); private: struct udev *udev; struct udev_monitor *monitor; QSocketNotifier *notifier; };
USBWatcher.cpp
#include "USBWatcher.h" #include <QDebug> #include <QFile> #include <QSocketNotifier> USBWatcher::USBWatcher(QObject *parent): QObject(parent) { udev = udev_new(); if (!udev) { qWarning() << "Failed to create udev context"; return; } // 创建一个udev监视器,监听所有设备事件 monitor = udev_monitor_new_from_netlink(udev, "udev"); udev_monitor_filter_add_match_subsystem_devtype(monitor, "usb", NULL); udev_monitor_enable_receiving(monitor); // 获取监视器的文件描述符,并设置为Qt的信号触发器 int fd = udev_monitor_get_fd(monitor); notifier = new QSocketNotifier(fd, QSocketNotifier::Read, this); connect(notifier, &QSocketNotifier::activated, this, &USBWatcher::handleDeviceChange); connect(this, SIGNAL(usbDeviceConnected()), parent, SLOT(USBDeviceConnected())); // 父类接收信号槽函数需自己实现。 connect(this, SIGNAL(usbDeviceDisconnected()), parent, SLOT(USBDeviceDisconnected())); // 父类接收信号槽函数需自己实现。 CheckConnectedUSBDevices(); } void USBWatcher::CheckConnectedUSBDevices() { QFile file("/proc/mounts"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Error opening /proc/mounts"; } file.seek(0); QTextStream in(&file); QString line = in.readLine(); if(line.contains("/usb/sd")) { emit usbDeviceConnected(); file.close(); return ; } while(!line.isNull()) { line= in.readLine(); if(line.contains("/usb/sd")) { emit usbDeviceConnected(); file.close(); return ; } } file.close(); } void USBWatcher::handleDeviceChange() { // 从udev监视器接收设备事件 struct udev_device *dev = udev_monitor_receive_device(monitor); if (dev) { const char *action = udev_device_get_action(dev); if (action) { QString devnode = udev_device_get_devnode(dev); if (devnode.startsWith("/dev/bus/usb")) { if (QString(action) == "add") emit usbDeviceConnected(); else if (QString(action) == "remove") emit usbDeviceDisconnected(); } } udev_device_unref(dev); } }
Linux udev 检测U盘插拔
于 2024-07-05 09:10:26 首次发布