Kill sleeping process when starting new one

Viewed 72

i have some Watcher.sh script running on a directory /foo/bar. When something happens in /foo/bar it starts another script (Updater.sh) which first sleeps for 30 seconds and then do stuff. The Watcher.sh script is managed by supervisor, which is configured to restart the script if it ends. So when there was a change in /foo/bar and the Updater.sh is started (in a subprocess), the Watcher script should end and get started again by supervisor. If there is a second change in /foo/bar the new Updater.sh script should end the first one and start again its 30 second sleep before doing stuff.

Watcher.sh script:

#!/usr/bin/env bash

echo "Started inotifywait with $BASHPID ID"
inotifywait -q -e modify,move,create,delete /foo/bar

/updater.sh &

Updater.sh script:

#!/usr/bin/env bash

echo "Start Update process $BASHPID"
FILE=/var/run/updater.pid
if test -f "$FILE" ; then
  kill -9 `cat /var/run/updater.pid`
  rm /var/run/updater.pid
fi

echo $BASHPID > /var/run/updater.pid
echo "Change in /foo/bar, reload soon"
sleep 30
supervisorctl reload

My problem is that it just don't happen. The Watcher.sh script is restarted, but the Updater.sh script is not killed at all. I checked the /var/run/updater.pid which is definitely set after the first change, but it just don't enter the if case and even when it does, it does not continue after the kill.

Would be great if somebody knows where i do something wrong, it should be simple right?..

EDIT 1: Use the following code in the updater.sh to not listen on a pid file

if ps -ef | grep -vE "grep|$BASHPID" | grep updater | awk '{print $2}' ; then
  echo "Kill it"
  kill -9 `ps -ef | grep -vE "grep|$BASHPID" | grep updater | awk '{print $2}'`
fi
0 Answers
Related