How do I (recursively?) monitor contents of new directories using inotify?

StarShire picture StarShire · Nov 12, 2013 · Viewed 8.7k times · Source

Firstly, I want to start by using inotify to monitor a specific directory (the main directory) for files and sub-directories. If a new directory is added into this main directory, how would I make sure to monitor this sub-directory with inotify? How would I monitor a new directory within this sub-directory of the main directory?

I think adding it to the watch is easy by using the inotify_add_watch() function but I do not know how to get the correct relative path address of files and directories within sub-directories (to use for like Dropbox-like syncing in a different location while maintaining the correct directory tree, for example).

Answer

asalic picture asalic · Nov 12, 2013

Well the fastest to implement (but not the fastest in reality) would be to:

  1. Create the initial tree of directories by recursively exploring the children; An example in C/Linux can be found here:

    http://www.lemoda.net/c/recursive-directory/

  2. Add a watch for each subdirectory; When something has been modified or changed you can parse all children recursively and see the differences. Something similar was discussed here: How to monitor a folder with all subfolders and files inside?

  3. If this solution doesn't appeal to you, you might try to do a polling mechanism such that you must re-check the whole structure using a thread at a certain time interval.

Hope it helps!