This is a translation from this article which is published in Dutch
During our work at Octrooicentrum Nederland somebody came up with the following question. During the night a file was created in a directory and he wanted to know who (which process) was responsible for that. My first reaction was: “Can’t be done”.
However, that evening I thought of
inotify which could be of help.
inotify you can watch your file system
and get notified when “something” (read, write, create, etc.)
happens. For (much) more detailed information look in inotify(7).
You can install the tools with:
% apt-get install inotify-tools
And with that you get two tools
The inotify framework has a configurable limit on how many directories
can be watched at once. To increase this a bit you need to write
a value to a file under
/proc, like so:
% sudo -s # echo $((2 ** 16)) > /proc/sys/fs/inotify/max_user_watches
64K should be enough for everyone.
inotifywait works with:
% inotifywait -m -r --format '%:e %f' ~ Setting up watches. Beware: since -r was given, this may take a while! Watches established.
-m: keep waiting;
--format '%:e %f': change the output (see inotifywait(1));
Now, I’m going to create a file in my home directory:
% touch bliep
And in my other terminal window I see output scrolling by, among which:
CREATE bliep OPEN bliep ATTRIB bliep CLOSE_WRITE:CLOSE bliep
As you can see, the file
~/bliep has been created.
Getting the process
Note: the following creates a blatant race condition, so this is not bullet proof.
inotifywait and let it trigger for the creation of the
bliep. If it is created try to get to the creating process (if
% inotifywait -m -r --format '%:e %f' ~ | grep -q 'CREATE bliep' && \ lsof -t ~/bliep | xargs pstree -a -h
Which should be fairly obvious to the trained Unix eye. So if I type the following in one terminal:
% touch bliep && tail -f bliep
inotifywait pipeline will output:
tail -f bliep
Which says: the
tail -f is still tailing the file
touch command is not seen. So we have the culprit – well one
of them, at least.
With inotify you can probably imagine other uses. One idea may be that of a realtime backup (this might even be already implemented by someone).
Other usefull tools based on
- cron-like daemon with support for filesystem events
- tail replacement with inotify, probably faster than GNU tail -f
You can find more information in this article, which is authored by the original author of inotify Robert Love.