2018/07/23

bash script to kill another script by pid file

the idea is to get the pid from a running script and save it to a file, so we can retrieve the id and kill the process. Also it should kill child processes

to create the file, during the script we must do (replace /home/mantener/var/run with another dir of your liking):

minombre=$(basename $0)
pidfile=/home/mantener/var/run/$minombre.pid
echo $$ >$pidfile

 
 and the script to make use of the pid file could be:

#!/bin/bash
pidfile=/home/mantener/var/run/$1.pid

if [ ! -f $pidfile ] ; then
   echo missing $pidfile !
   logger $0 missing $pidfile !
   exit -1
fi

cualpid=$(cat $pidfile)

# get child processes
resto=$(ps --ppid $cualpid -o pid --no-headers)

echo killing $1
kill -9 $cualpid

while IFS= read -r line ; do
    echo killing $line
    kill -9 $line
done <<< "$resto"

rm $pidfile

No comments:

Post a Comment