0

using centos5 below is my shell script. I want to prevent it from multiple instance.. but it doesn't work with if I fir "kill -9" option. also I doubt It will work on reboot. Is there anyway to apply this logic ? which can also handle kill -9 or reboot or any signal which cause manual exit of the script ?

[root@manage aaa]# cat script.sh

#!/bin/sh
set -e

scriptname=$(basename $0)
pidfile="/var/run/${scriptname}"

# lock it
exec 200>$pidfile
flock -n 200 || exit 1
pid=$$
echo $pid 1>&200

#### SCRIPT CODE
Jatin Bodarya
  • 1,425
  • 2
  • 20
  • 32

2 Answers2

1

Try using the flock command. From the man page:

(
  flock -n 9 || exit 1
  # ... commands executed under lock ...
) 9>/var/lock/mylockfile
Christopher Creutzig
  • 8,656
  • 35
  • 45
  • ( flock -n 9 || exit 1 # ... commands executed under lock ... sleep 30 ) 9>/var/lock/mylockfile I have tried with above script. but if i kill it using "kill -9" it is not alowing me to execute script again till 30 seconds – Jatin Bodarya Sep 08 '14 at 06:39
  • The parentheses start a subshell which you need to also kill. (kill -9 should not be your normal mode of operation anyway, but that's just my personal opinion.) – Christopher Creutzig Sep 08 '14 at 07:17
  • yes,I have killed both of the processes. it will work on reboot or improper exit rather than kill -9 ? – Jatin Bodarya Sep 08 '14 at 07:30
0

You can resolv this problens using this logic.

Start the lock

verify, is locked? no continue, or stop...

My script.

#!/bin/bash

LOCK=/var/run/redundancia.lock
LOG=/var/log/redundancia.log

#----------------------------------------------------------------

control_c () {
        echo -e "\nScript stoped:  `date +%d/%m/%Y%t%T`" >> $LOG
        rm $LOCK &>/dev/null
        exit 0
}

trap control_c INT HUP TERM

if [ ! -f $LOCK ]
then
    touch $LOCK 
# Your code....
else
    echo "This script is running"
    exit 0
fi

Sorry my bad english ;/