linux qt 检测U盘热插拔的方法与代码
时间: 2024-03-21 18:41:59 浏览: 292
qt 监测u盘设备热插拔
4星 · 用户满意度95%
可以使用Linux下的udev来检测U盘的插拔,并通过Qt的信号槽机制实现。
以下是一个简单的示例代码:
```c++
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QSocketNotifier>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QRegExp>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <libudev.h>
class UdevMonitor : public QObject
{
Q_OBJECT
public:
explicit UdevMonitor(QObject *parent = 0)
: QObject(parent)
, m_udevContext(udev_new())
{
if (!m_udevContext) {
qCritical() << "Failed to create udev context.";
return;
}
m_udevMonitor = udev_monitor_new_from_netlink(m_udevContext, "udev");
if (!m_udevMonitor) {
qCritical() << "Failed to create udev monitor.";
return;
}
udev_monitor_filter_add_match_subsystem_devtype(m_udevMonitor, "block", "disk");
if (udev_monitor_enable_receiving(m_udevMonitor) < 0) {
qCritical() << "Failed to enable udev monitoring.";
return;
}
m_notifier = new QSocketNotifier(udev_monitor_get_fd(m_udevMonitor), QSocketNotifier::Read, this);
connect(m_notifier, &QSocketNotifier::activated, this, &UdevMonitor::handleUdevEvent);
}
~UdevMonitor()
{
if (m_notifier)
delete m_notifier;
if (m_udevMonitor)
udev_monitor_unref(m_udevMonitor);
if (m_udevContext)
udev_unref(m_udevContext);
}
signals:
void deviceAdded(const QString &devicePath);
void deviceRemoved(const QString &devicePath);
private slots:
void handleUdevEvent()
{
struct udev_device *udevDevice = udev_monitor_receive_device(m_udevMonitor);
if (udevDevice) {
QString devicePath = QString::fromUtf8(udev_device_get_devnode(udevDevice));
QString action = QString::fromUtf8(udev_device_get_action(udevDevice));
if (action == "add")
emit deviceAdded(devicePath);
else if (action == "remove")
emit deviceRemoved(devicePath);
udev_device_unref(udevDevice);
}
}
private:
struct udev *m_udevContext = nullptr;
struct udev_monitor *m_udevMonitor = nullptr;
QSocketNotifier *m_notifier = nullptr;
};
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
UdevMonitor monitor;
QObject::connect(&monitor, &UdevMonitor::deviceAdded, [](const QString &devicePath) {
qDebug() << "Device added:" << devicePath;
});
QObject::connect(&monitor, &UdevMonitor::deviceRemoved, [](const QString &devicePath) {
qDebug() << "Device removed:" << devicePath;
});
return app.exec();
}
#include "main.moc"
```
这个示例代码使用了libudev库来监听U盘的插拔事件,当U盘插入或拔出时,会发出相应的信号。你可以在deviceAdded和deviceRemoved信号的槽函数中做出相应的处理,比如挂载或卸载U盘。
阅读全文