From 3ad1c33a84ed6c56931c6841dad81a3df8041840 Mon Sep 17 00:00:00 2001 From: Zhang Sheng Date: Fri, 20 Nov 2026 11:48:24 +0800 Subject: [PATCH] fix: prevent file watcher dead after stopping one of same inode paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added reference-counted registry to prevent GLib's inotify backend from canceling shared watch descriptors when multiple paths point to the same inode (via symlinks or bind mounts). Previously, if two DWatcher instances monitored the same directory through different paths (e.g., directory and symlink), stopping one would cancel the underlying inotify watch, leaving the other watcher permanently deaf. The new MonitorKeepAliveRegistry tracks active watchers per inode, only canceling the shared monitor when the last watcher for that inode stops. This ensures remaining watchers continue receiving events. Two test cases verify both that stopping one path does not affect others and that a fresh watcher works after all previous watchers for an inode are stopped. Influence: 1. Test monitoring a directory and its symlink simultaneously, then stop one watcher 2. Verify the remaining watcher still receives file creation/deletion events 3. Test scenario with multiple bind mounts or hard links to same directory 4. Test that after stopping all watchers for an inode, new watchers work correctly 5. Ensure non-local file paths (non-inotify cases) fall back to direct cancel without regression fix: 修复停止同一inode路径之一后文件监视器失效的问题 添加了引用计数注册表,以防止在多个路径指向同一inode(通过符号链接或绑定 挂载)时,GLib的inotify后端取消共享监视描述符。之前,如果两个DWatcher实 例通过不同路径(例如目录和符号链接)监视同一目录,停止其中一个会取消底层 的inotify监视,导致另一个监视器永久失效。新的MonitorKeepAliveRegistry按 inode跟踪活动监视器,仅在该inode的最后一个监视器停止时才取消共享监视器。 这确保了剩余的监视器能继续接收事件。两个测试用例验证了停止一个路径不影响 其他路径,以及在该inode的所有先前监视器停止后,新的监视器仍能正常工作。 Influence: 1. 测试同时监视目录及其符号链接,然后停止其中一个监视器 2. 验证剩余的监视器仍能接收文件创建/删除事件 3. 测试具有多个绑定挂载或硬链接到同一目录的场景 4. 测试在停止某个inode的所有监视器后,新的监视器能正常工作 5. 确保非本地文件路径(非inotify情况)回退到直接取消而不会引起回归 Log: PMS: Task-398995 --- autotests/dfm-io-tests/tst_dfm_io.cpp | 80 ++++++++++++++++++++ src/dfm-io/dfm-io/dwatcher.cpp | 101 +++++++++++++++++++++++-- src/dfm-io/dfm-io/private/dwatcher_p.h | 1 + 3 files changed, 177 insertions(+), 5 deletions(-) diff --git a/autotests/dfm-io-tests/tst_dfm_io.cpp b/autotests/dfm-io-tests/tst_dfm_io.cpp index da783bca..f96ef5fc 100644 --- a/autotests/dfm-io-tests/tst_dfm_io.cpp +++ b/autotests/dfm-io-tests/tst_dfm_io.cpp @@ -3,6 +3,16 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include +#include +#include +#include +#include +#include +#include + +#include + +USING_IO_NAMESPACE class tst_DfmIO : public QObject { @@ -12,6 +22,13 @@ private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void initialization_test(); + + // GLib inotify后端按inode共享watch描述符:对同一inode的两条路径分别建监视器后 + // cancel其一,存活者会永久收不到事件。用symlink构造同inode双路径精确复现 + // (g_file_new_for_path不解析symlink,两条路径各自建订阅、内核共享wd; + // 不能用"/dir/."作第二路径——g_file_new_for_path会把它canonicalize成"/dir")。 + void stopOnePathKeepsOtherPathMonitored(); + void watcherRecoversAfterAllPathsStopped(); }; void tst_DfmIO::initTestCase() @@ -30,5 +47,68 @@ void tst_DfmIO::initialization_test() QVERIFY(true); } +static bool createEmptyFile(const QString &path) +{ + QFile f(path); + return f.open(QIODevice::WriteOnly); +} + +void tst_DfmIO::stopOnePathKeepsOtherPathMonitored() +{ + QTemporaryDir tmpDir; + QVERIFY(tmpDir.isValid()); + const QString root = tmpDir.path(); + const QString link = root + "/sibling-link"; + QVERIFY(QFile::link(root, link)); + + DWatcher rootWatcher(QUrl::fromLocalFile(root)); + DWatcher linkWatcher(QUrl::fromLocalFile(link)); + QVERIFY(rootWatcher.start()); + QVERIFY(linkWatcher.start()); + + QSignalSpy rootAdded(&rootWatcher, &DWatcher::fileAdded); + QSignalSpy linkAdded(&linkWatcher, &DWatcher::fileAdded); + + // 停掉经由symlink路径的监视器:不应cancel共享订阅 + QVERIFY(linkWatcher.stop()); + + QVERIFY(createEmptyFile(root + "/after-stop.txt")); + + // root监视器应收到created事件 + QVERIFY(rootAdded.wait(3000)); + QCOMPARE(linkAdded.count(), 0); // 已停止的监视器不得收事件 + + QVERIFY(rootWatcher.stop()); + QFile::remove(root + "/after-stop.txt"); +} + +void tst_DfmIO::watcherRecoversAfterAllPathsStopped() +{ + QTemporaryDir tmpDir; + QVERIFY(tmpDir.isValid()); + const QString root = tmpDir.path(); + const QString link = root + "/sibling-link"; + QVERIFY(QFile::link(root, link)); + + { + DWatcher rootWatcher(QUrl::fromLocalFile(root)); + DWatcher linkWatcher(QUrl::fromLocalFile(link)); + QVERIFY(rootWatcher.start()); + QVERIFY(linkWatcher.start()); + QVERIFY(linkWatcher.stop()); + QVERIFY(rootWatcher.stop()); + } // 全部停止:最后一个stop应cancel并析构寄存的监视器,GLib状态自净 + + DWatcher freshWatcher(QUrl::fromLocalFile(root)); + QVERIFY(freshWatcher.start()); + QSignalSpy freshAdded(&freshWatcher, &DWatcher::fileAdded); + + QVERIFY(createEmptyFile(root + "/after-all-stopped.txt")); + QVERIFY(freshAdded.wait(3000)); + + QVERIFY(freshWatcher.stop()); + QFile::remove(root + "/after-all-stopped.txt"); +} + QTEST_MAIN(tst_DfmIO) #include "tst_dfm_io.moc" diff --git a/src/dfm-io/dfm-io/dwatcher.cpp b/src/dfm-io/dfm-io/dwatcher.cpp index facbca06..b88ac805 100644 --- a/src/dfm-io/dfm-io/dwatcher.cpp +++ b/src/dfm-io/dfm-io/dwatcher.cpp @@ -8,9 +8,82 @@ #include "private/dwatcher_p.h" #include +#include +#include +#include +#include + +#include USING_IO_NAMESPACE +namespace { + +// 同一inode经不同路径(多挂载点/bind)监视时,GLib的inotify后端按inode共享 +// 内核watch描述符:任一监视器cancel会误删共享订阅,使其它路径的存活监视器永久失聪, +// 且残留的path桶会让后续新建监视器挂到死订阅上。注册表按(st_dev, st_ino)对活跃监视器 +// 计数:仍有同inode其它活跃者时,停止方只寄存GFileMonitor而不cancel;最后一个活跃者 +// 停止时才统一cancel并析构全部寄存的监视器,此时GLib状态自净。 +// key编码将st_dev截断为32位:不同文件系统key冲突只会让监视器延迟清理,不会误删订阅。 +class MonitorKeepAliveRegistry +{ +public: + static MonitorKeepAliveRegistry &instance() + { + static MonitorKeepAliveRegistry registry; + return registry; + } + + void addActive(quint64 key) + { + if (key == 0) + return; + QMutexLocker locker(&mutex); + ++refCounts[key]; + } + + // 停止时调用:同inode仍有其它活跃监视器时寄存monitor(不cancel)并返回true; + // 否则清除计数,并通过doomed交还该inode全部寄存的监视器,由调用方在锁外cancel析构 + bool retainOrPark(quint64 key, GFileMonitor *monitor, QList *doomed) + { + doomed->clear(); + if (key == 0) + return false; + QMutexLocker locker(&mutex); + const int remaining = refCounts.value(key) - 1; + if (remaining > 0) { + refCounts[key] = remaining; + parked[key].append(monitor); + return true; + } + refCounts.remove(key); + *doomed = parked.value(key); + parked.remove(key); + return false; + } + +private: + QMutex mutex; + QHash refCounts; + QHash> parked; +}; + +// 从监视目标GFile取(st_dev, st_ino)编码key;非本地路径或stat失败返回0(走直接cancel) +quint64 inodeKeyOf(GFile *gfile) +{ + if (!gfile) + return 0; + g_autofree gchar *path = g_file_get_path(gfile); + if (!path) + return 0; + struct stat st; + if (::stat(path, &st) != 0) + return 0; + return (quint64(st.st_dev) << 32) | quint32(st.st_ino); +} + +} // namespace + /************************************************ * DWatcherPrivate ***********************************************/ @@ -43,7 +116,6 @@ GFileMonitor *DWatcherPrivate::createMonitor(GFile *gfile, DWatcher::WatchType t gmonitor = g_file_monitor_file(gfile, flags, cancel, &gerror); } - if (!gmonitor) { setErrorFromGError(gerror); @@ -104,7 +176,7 @@ void DWatcherPrivate::watchCallback(GFileMonitor *monitor, GFile *child, GFile * watcher->fileRenamed(childUrl, otherUrl); break; - //case G_FILE_MONITOR_EVENT_MOVED: + // case G_FILE_MONITOR_EVENT_MOVED: default: g_assert_not_reached(); break; @@ -200,15 +272,32 @@ bool DWatcher::start(int timeRate) g_signal_connect(d->gmonitor, "changed", G_CALLBACK(&DWatcherPrivate::watchCallback), this); + // key在start时缓存:stop时目标可能已被删除重建(inode变化),重stat会减错计数 + d->inodeKey = inodeKeyOf(d->gfile); + MonitorKeepAliveRegistry::instance().addActive(d->inodeKey); + return true; } bool DWatcher::stop() { if (d->gmonitor) { - g_file_monitor_cancel(d->gmonitor); - g_object_unref(d->gmonitor); - d->gmonitor = nullptr; + QList doomed; + if (MonitorKeepAliveRegistry::instance().retainOrPark(d->inodeKey, d->gmonitor, &doomed)) { + // 同inode仍有其它路径在监视:不cancel(会误删GLib共享订阅使存活者永久失聪), + // 仅断开changed回调静默本对象,监视器交由注册表持有 + g_signal_handlers_disconnect_by_data(d->gmonitor, this); + d->gmonitor = nullptr; + } else { + g_file_monitor_cancel(d->gmonitor); + g_object_unref(d->gmonitor); + d->gmonitor = nullptr; + for (GFileMonitor *monitor : doomed) { + g_file_monitor_cancel(monitor); + g_object_unref(monitor); + } + doomed.clear(); + } } if (d->gfile) { @@ -216,6 +305,8 @@ bool DWatcher::stop() d->gfile = nullptr; } + d->inodeKey = 0; + return true; } diff --git a/src/dfm-io/dfm-io/private/dwatcher_p.h b/src/dfm-io/dfm-io/private/dwatcher_p.h index c25eb54e..3e5f1b01 100644 --- a/src/dfm-io/dfm-io/private/dwatcher_p.h +++ b/src/dfm-io/dfm-io/private/dwatcher_p.h @@ -32,6 +32,7 @@ class DWatcherPrivate DWatcher *q { nullptr }; GFileMonitor *gmonitor { nullptr }; GFile *gfile { nullptr }; + quint64 inodeKey { 0 }; // start时缓存的(st_dev, st_ino),保证stop与start对同一inode计数 int timeRate { 200 }; DWatcher::WatchType type = DWatcher::WatchType::kAuto;