C++ WinApi: ReadDirectoryChangesW() Receiving Double Notifications

前端 未结 2 1428
太阳男子
太阳男子 2021-01-03 23:36

I try to understand ReadDirectoryChangesW function so I can be effectively informed on change of content in several directories (files overwrit

相关标签:
2条回答
  • 2021-01-03 23:43

    ReadDirectoryChangesW() has a very myopic view of the file system. It sees every change to the file system and dutifully reports them. And yes, there is often more than one when you write to a file. It is an implementation detail of the particular file system you are using, but any common one in Windows also keeps a directory entry for a file that stores metadata for the file.

    So you see the write for the file data. But you also see it changing the directory entry. In particularly the file size, likely to change when you write a file and add data to the file. And the last-write and last-access timestamps recorded in the directory entry. The api is otherwise blind to the kind of change being made, it only sees the low-level write. It is also completely unaware of what particular process asked for the write.

    This is something you will have to deal with, there is no way to distinguish these writes. All that you know is "the file was changed". How, why, by whom and how often is entirely undiscoverable.

    Something else you will have to deal with is that, at the time the notification is generated, the process that writes the file is very likely to still have a lock on the file. Which prevents you from doing anything useful with the file yourself. Like reading the file or copying it is likely to fail. You have to wait until the process is done with the file and has closed its handle to the file. There's no way to discover this, other than by trying to open the file yourself and deny any sharing. This requires a timer, periodically trying to acquire a lock on the file yourself. Once you got that plumbing in place, getting more than one change notification for the file doesn't matter anymore.

    0 讨论(0)
  • 2021-01-03 23:52

    This is the result operation of the running code simultaneously with the procmon logging after file save in notepad. There are two notifies from ReadDirectoryChangesW() and two notifies from procmon. 2 IRP_MJ_WRITE 1 from Notepad (WriteFile) 1 from System Cache Manager (CcWriteBehind) procmon

    0 讨论(0)
提交回复
热议问题