Linux – Question About inotifywait

inotifylinux

Here is an example shell script I'm looking at implementing using inotify:

inotifywait -mrq -e close_write -e create -e delete -e move /var/www | while read file;
do   
    rsync -av /var/www1/ /var/www2/  
done

Let's say rsync takes 30 seconds to complete.

If there are 10 inotify events within 5 seconds, will there be 10 processes of rsync running the same job at the same time?

OR

Will there only be one rsync job that is run 10 times, one after the other?

Best Answer

They will be run one after another unless you background the rsync with a & at the end.

This will run them concurrently which is not what you want:

inotifywait -mrq -e close_write -e create -e delete -e move /var/www | while read file
do   
    rsync -av /var/www1/ /var/www2/  &
done

You probably also don't want it run ten times consecutively. This may be what you're after:

while inotifywait -rq -e close_write -e create -e delete -e move /var/www
do   
    rsync -av /var/www1/ /var/www2/  
done

Also, be aware that running inotifywait recursively on a large /var/www may take a while to set up on each invocation. You may want to limit its scope to only watching active subdirectories or just use cron to periodically run rsync.

Edit:

Try this demo:

$ mkdir inotifytest
$ cd inotifytest
$ echo something > testfile
$ while inotifywait -rq -e access .; do echo "processing"; sleep 3; done    # test 1

Now in another terminal, do this:

$ cd inotifytest
$ for i in {1..10}; do cat testfile > /dev/null; done

In the first terminal you should see "processing" one time. If you do the for/cat loop (which represents files being added or deleted in your directories) again, you'll see it again.

Now in the first terminal, interrupt the loop with Ctrl-C and start this loop:

$ inotifywait -mrq -e access .| while read file; do echo "processing"; sleep 3; done    # test 2

In the second terminal, run the for/cat loop again. This time in the first terminal you'll see "processing" ten times with a three second pause between each one (representing the time it takes rsync to complete. Now if you were to run the for loop several times in rapid succession you might be waiting all day.