I made a script to invoke inotifywait
.
It works fine, but I sometimes want to stop it.
How do I stop the last inotifywait
instance?
I cannot understand how to use inotify_rm_watch
which I understand is used to close it.
7341 ? S 0:00 inotifywait -m /home/andy/Downloads/ --format %w
The
inotify_rm_watch
you refer to is the API (C-function) you would use when writing a "real" program (in C or something similar), not a script. So it doesn't apply to your situation.If you want to stop
inotifywait
you can do it as with any other program:Either issue
ps -ef | grep inotifywait
, pick the PID (in your example presumably7341
) and then send it a signal:kill 7341
Or use the convenience script
killall
which kills all programs with a given name.killall
is usually installed by default.killall inotifywait
WHAT IS THE PROBLEM WHEN USING
kill <pid>
?You might have more than one
inotifywait
processes because other scripts can useinotifywait
independently. So using this commandps -ef | grep inotifywait
to find the right PID is not the best thing to do because you need to have a good assumption whichinotifywait
process belongs to your script. So, you might end up killing the wrong PID. Besides, the commandkillall inotifywait
is more aggressive than the previous one. However, if you really don't care other system is using inotifywait, you use the aggressive command.MY BEST WAY TO KILL
inotifywait
PROCESS FOR EACHinotifywait
instanceYou can create a file flag to terminate inotifywait for a specific running script. Below scripts is example how you start the inotify script, stop it, or even test if it's running for that specific inotify PID.
You can watch this action from the log file
$REPORT_FILE
To start monitoring, you can use:
To test the script with if inotifywait is running you do this command:
So, to stop the inotify running process, you just need to run the same script with
With this method, you don't need to know what is the process ID for that inotifywait process.
HOW DOES IT WORK?
You notice that I have 2 files to monitor
$flag $test
from theinotifywait
command so if I make changes to the$flag
file, the modify even will be triggered immediately and I can use this opportunity to stop the PID process inside theinotifywait loop
. Also, you can see that the script actually stores an actual pid ofinotifywait
atpid="inotify-test.pid"
. So you can manually terminate theinotifywait
process using this correct pid.This kills all the instances of
inotifywait
:When using
inotifywait --daemon
you never get the process's ID.If you're like me and don't want to kill ALL the instances of inotifywait indiscriminately you can instead use
nohup
andinotifywait --monitor
.Here's how I'm using it in my bash scripts. It allows me to not disturb other running instances of
inotifywait
:The input and output redirection commands (
</dev/null >/dev/null 2>&1 &
) comes from this answer on StackOverflow