Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindFirstChangeNotification is notifying about changes twice

I want to monitor a folder in my file system. Let say I want to monitor the folder: C:\MyNewFolder

I have this code to do it:

HANDLE  ChangeHandle=FindFirstChangeNotification(_T("C:\\\MyNewFolder"),FALSE,FILE_NOTIFY_CHANGE_LAST_WRITE);
for(;;)
{
    DWORD Wait=WaitForSingleObject(ChangeHandle,INFINITE);
    if (Wait == WAIT_OBJECT_0)
    {
        MessageBox(NULL,_T("Change"),_T("Change"),MB_OK);
        FindNextChangeNotification(ChangeHandle);
    }
    else
    {
        break;
    }
}

I want to have a messagebox that notifying me about any file change in my folder. That code works fine but I have one problem. The problem is that I got 2 notification for each change. What is the problem with my code? Thanks.

like image 781
Ofer Avatar asked Apr 07 '13 17:04

Ofer


2 Answers

This is entirely normal. A change to a file usually involves a change to the file data as well as a change to the directory entry. Metadata properties like the file length and the last write date are stored there. So you'll get a notification for both. ReadDirectoryChangesW() doesn't otherwise distinguish between the two.

This is not different from a process making multiple changes to the same file. Be sure to be able to handle both conditions. This usually involves a timer so you don't go overboard with the number of operations you perform on a notification. Such a timer is also often required because the process that is changing the file still has a lock on it that prevents you from doing anything with the file. Until the process closes the file, an indeterminate amount of time later.

like image 51
Hans Passant Avatar answered Nov 14 '22 22:11

Hans Passant


What you're probably seeing is multiple changes to the one file (e.g. a file being created, and then written to, or a file being written to multiple times, etc). Unfortunately FindFirstChangeNotification doesn't tell you what has actually happened.

You're better off using ReadDirectoryChangesW for file notification as it will actually tell you what has changed.

like image 26
Jonathan Potter Avatar answered Nov 14 '22 23:11

Jonathan Potter