Reputation: 6911
I'm seeing a strange behavior that I didn't see in the documentation. Here's my test code:
HANDLE h = FindFirstChangeNotification(L"test_dir", FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);
printf("%p %u\n", h, GetLastError());
while (true) {
WaitForSingleObject(h, INFINITE);
BOOL b = FindNextChangeNotification(h);
printf("%d %u\n", b, GetLastError());
}
The code works as expected by printing a message every time I modify a file in the folder. But if I remove the folder, it enters an infinite loop, returning success every time.
I'm afraid that if a user removes the target folder by mistake or for any other reason, the program is going to be spinning the CPU, and I'll have no way to detect this. I can check whether the folder is gone, but it doesn't feel like a clean solution, and also it can be recreated, in which case the loop keeps spinning.
When the folder is removed for good, I get an error from FindNextChangeNotification
as I expected. But if it's removed to the recycle bin, I get an infinite loop.
Upvotes: 0
Views: 367
Reputation: 3400
You have the while(true) loop. Of course, it will be an infinite loop. You need to check the return value (b) in the loop condition in order to quit on FALSE value.
Update according to the change in the question: Moving the file to the recycle bin is not "strict removing", it is moving only. So, the folder still exists, but in another place, in the recycle bin, so no notifications should arrive on such a move. I don't have the solution at the moment, so I would suggest to monitor this folder from the upper folder using the FILE_NOTIFY_CHANGE_DIR_NAME parameter and tracking this folder name to make sure that it is not moved. But in this case you could be forced to distinguish between moving to recycle bin and another place and so on...
Upvotes: 2
Reputation: 11321
You should watch for the changes in the parent directory as well. The example shows how to wait for two (or more) events:
https://learn.microsoft.com/en-us/windows/win32/fileio/obtaining-directory-change-notifications
If your directory is deleted - FindCloseChangeNotification
the handle; if it is created - re-open it.
Upvotes: 1