You need to use inotify.
stat () is worse than useless for this purpose. If st_mtime is different from the last one when you checked it, it means that the file has changed, and everything is fine.
But what if st_mtime is the same? There is no guarantee that this means that the file has not been altered in the granularity of the time stamp of the file system. For example, on ext3, graininess tends to be a few milliseconds. You cannot count on the time difference between your checks; the important thing is how quickly the file could be changed after the last time your process checked it.
So, even if st_mtime is the same, you cannot be sure that the file has not changed. Therefore, you must assume that it is, and it makes no sense to mislead yourself by performing the test.
The same problems apply to st_ino if you expect a file (of this name) to be replaced with a new file in the create-and-replace operation. the inode numbers can be reused, and after several replacements, the file (by name) can again return to its original inode number.
The same applies to file size, or even to creating a file hash. All that allows you to determine that the file has changed. None of these methods allows you to be completely sure that it has not changed, even hashing (although this approaches confidence).
Do not waste your time on stat (), this is a crazy errand.
source share