I want to monitor USB-Keys on my system. I know they are always mounted in /media so I use inotify to monitor /media. Some USB Keys create a folder (e.g. sda) when plugged which
The subfolder problem with inotify is well known and easily reproduced:
Start inotifywait watching an empty tmp directory:
inotifywait -e create -m -r --format '%:e %f' ./tmp
In another shell enter:
mkdir tmp/0 tmp/0/0 tmp/0/0/0 tmp/0/0/0/0
You will most likely only get a notification for the first subdirectory.
CREATE:ISDIR 0
The distinct possibility of losing events (particularly subdirectory creation events) between the time a directory is created, your app gets notified, and a new inotify watch is added, makes recursive monitoring too unreliable. The only safe option is to scan contents of newly created directories.
From the inotify doc under Limitations and caveats:
If monitoring an entire directory subtree, and a new subdirectory is created in that tree, be aware that by the time you create a watch for the new subdirectory, new files may already have been created in the subdirectory. Therefore, you may want to scan the contents of the subdirectory immediately after adding the watch.