Add a watch specifying the path to the directory the file or directory is in, for IN_MOVE_FROM
and IN_MOVED_TO
events. Whenever you receive such an event, compare the event name
field to the file or directory name(s) you are interested in.
In general, you probably end up watching for IN_CLOSE_WRITE
and IN_MOVED_TO
events and their name
fields if one of the interesting files have been created or modified; and IN_DELETE
and IN_MOVED_FROM
events if an interesting file vanishes.
Inotify events are anchored in the parent directory inode. That is, if a directory you have a watch descriptor for is moved, you get an IN_MOVE_SELF
event, but you keep receiving events for files and directories inside it even though it now resides somewhere else.
If you are interested in specific paths, regardless of whether they exist when the program is started or not – you cannot set a watch on a directory that does not exist yet – you'll need to create a watch descriptor for every directory along that path up to the root directory, like a chain. Some of these you may need to create dynamically. If one of them is deleted or moved, IN_DELETE_SELF
or IN_MOVE_SELF
, it and all its dependent watch descriptors are to be deleted. Whenever an existing directory gets an IN_CREATE
or IN_MOVED_TO
event with name
being the name of an interesting subdirectory, you create a watch for it; but you also need to scan the subdirectory tree for further interesting sub-subdirectories, because those may already exist, or may have been created between the time you got this event and when you added a watch to the new subdirectory.
Because of that complexity, it is easier to use "flat" tree hierarchy, where you monitor a set of fixed directories that are required to exist when the program starts. (That is, you monitor those directories for new/deleted files and directories, but not their subdirectories.)