Re: Monitor a directory using WaitForMultipleObjects
Ganga Sridhar <gangasridhar@abosoftware.com> wrote:
I need to process the files in a directory immediately the moment it
gets deposited in a directory.
I am trying to achieve this by running WaitForMultipleObjects ,
FindFirstChangeNotificationAPI, FindNextChangeNotification in a While
loop in the Run() of one of my worker threads of my multithread
application.
I don't see FindNextChangeNotification call anywhere in your code.
I get the events for the files that were deposited after the
WaitForMultipleObjects was invoked in the while loop.
However those files that get deposited in the folder in the split of
second before the WaitForMultipleObjects is invoked are not getting
reported i.e. I am not getting their handles.
I believe you misinterpret your results. A state of the directory is
captured at the moment of FindFirstChangeNotification or
FindNextChangeNotification call. Any change since that moment would
result in the handle becoming signalled. The point at which you call
Wait* function on this handle is irrelevant.
This means it is a good idea to call FindNextChangeNotification soon
after Wait*, and before you actually process the contents of the
directory. Otherwise you may miss some changes. Consider this
pseudocode:
HANDLE h = FindFirstChangeNotification(...);
while (Wait(h)) {
ProcessFiles();
// A new file added here
FindNextChangeNotification(h);
}
ProcessFiles misses the new file, but FindNextChangeNotification takes
the snapshot with new file already in place. The handle won't become
signalled until another change occurs, so you miss a change. On the
other hand:
HANDLE h = FindFirstChangeNotification(...);
while (Wait(h)) {
// file A added here
FindNextChangeNotification(h);
// file B added here
ProcessFiles();
// file C added here
}
File A will not be considered a change since it is added before the
state is captured by FindNextChangeNotification. But it doesn't matter
since it will be handled by ProcessFiles anyway. File C will trigger a
change, handle will be signalled, so on the next iteration Wait() will
return immediately. File B is an interesting case: it will be processed
by ProcessFiles on this iteration, but it will also trigger a change and
cause another pass. So this approach may result in your doing extra work
in some cases (rescanning the files that you've already seen), but it's
better than missing some changes.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925