问题
I have been tweaking the example here to make it repeatedly watch a file for 'modifications'. My code is here. In my tests the inotify notification is only firing the first time the file is 'modified'(i.e. touch
'ed). Any subsequent modifications to the file are not causing any notifications to fire. stat
shows that the 'Modify' time has changed. Also, modifying the code to remove the watch and re-add each time a notification fires(i.e. move inotify_add_watch
and inotify_rm_watch
to be inside the while(1)
loop in my sample) did not help resolve this issue.
I was wondering if any one here could help with what I may be doing wrong. Also, although I have added a watch for IN_ALL_EVENTS
, I really only care about IN_MODIFY
events. Not sure if that makes any difference.
Also, does this use case not work? Should I change my approach to watch the directory instead? Please advice.
TIA.
Edit 1: As noted by themel, the handling of i
needed some fixing. However even the fixed version is not firing notifications for subsequent filesystem 'events'. Also, adding a watch on the directory as opposed to the file is exhibiting similar non-deterministic behavior.
Edit 2: I would like to get this asio + inotify example based on this answer to work. Unfortunately that example hasn't been working for me at all. Any help would be much appreciated. TIA.
回答1:
After themel's fix, your code works fine when watching a directory, in my tests. When watching a file, event->len
is zero, and your code ignores the notifications.
With the test for event->len
removed and all event->name
replaced by file_path
in the printf statements, it works fine when watching a file as well.
PS: Just noticed you mention touch
.
touch
sends the following events:
IN_OPEN
IN_ATTRIB
IN_CLOSE_WRITE
no IN_MODIFY
Also, don't test modification by editing it with vim
as I just did - it deletes the file while shuffling the working copy and the swap, which removes the watch. pico
works.
回答2:
Your handling of i
is broken, you never reset it to 0 in the loop. This causes any later inotify events to be considered only when they are longer than the longest event before them, which is not likely what you want.
Fixed version.
回答3:
when monitoring an individual file event->len will be 0 because the file name is not returned. I noticed a lot of the example programs have this issue.
来源:https://stackoverflow.com/questions/15228337/inotify-not-firing-notifications-on-file-modification