Why do inotify events fire more than once

Solution 1:

I've just had this using IN_CLOSE_WRITE and finally tracked down the problem. My original script was reading in mail from stdin line by line and then writing each line to the file. This was causing incron to fire on every line write. I saw this based on the number of incron events and how many lines were in the file.

I then changed the original script to read all of stdin in before writing the file. Once this was in place I no longer saw multiple incron executions on the same file.

Solution 2:

I don't have enough rep to post this as a comment, but are you sure that temporary, possibly-hidden files are not being created? I had a similar issue with inotifywait firing multiple times, but I realized it was because vim would create a .swp file when editing, which would fire an event when closing. It would also pick up the close event from the original file.

It sounds like you're noticing the event firing multiple files on the same file though, which is not something I've been able to reproduce -- this would only happen once for the temp file and once for the original.

I tried a quick test with nano and I don't think it creates a temp file at all (at least for the few character case), but is there anything else in your setup that could rely on similar behavior?

Solution 3:

I am not sure, but most probably the first write_close writes file attributes into it, like creation time, and only after that it writes actual data. In fact rsync creates a temp file and when everything is done it moves the temp file to the actual file in the same folder so it is easy to monitor has been normally created in when you use rsync, and move is an atomic operation. On the other hand there is something calle one shot in inotify, probably that using that we can trigger something on the first modify message, and as you suggested sleep for reasonable amount of time before starting the operation. I am digging this now, and will update when I find anything new. https://superuser.com/questions/1133642/traceing-the-moment-when-file-is-completely-copied-to-samba-share-with-inotify