Lock for this script

Hi,

My requirement is to service a process and below is the script which i wrote for that and works fine, I have kept it in a crontab and running this everyminute, how do I lock this if its already running and i dont want to open if its running and not completed yet.

The crontab need to run for the next minute after it completes running the older one.

#!/bin/ksh

while [ true ]; do

        i=$\(ps -ef | grep PROCESS_NAME |grep -v grep |wc -l\)

        if [ "$i" -lt 2 ]

        then

        echo "\`date '\+%Y-%m-%d-%H:%M:%S'\` WARNING !!! PROCESS IS DOWN"

        else

        echo "\`date '\+%Y-%m-%d-%H:%M:%S'\` PROCESS IS UP"

        fi

done

Help me to keep a lock for this, I am using AIX 5.3

Three options:
Don't run this from crontab but instead use a while loop with a sleep 60 at the end and background it. No chance of it doubleing up on itself then.

Or

Have your script look for 'itself' in the process table before doing anything, if it's finds itself there already, exit. You've already written the code to do this in the script you provided above, just have to duplicate it and change PROCESS_NAME to your script name.

Or

Start the script with this:

if [ -f /tmp/scriptlockfile ]
then
    exit 0
else
    touch /tmp/scriptlockfile
fi

and end it with:

rm -f /tmp/scriptlockfile

Yeah, what dragon said.

Personally, I like option 3. There's a million ways ya might get it done, but the three suggestions are probably the basis for most of 'em.

Keep in mind the potential use of the shell variables $! and $$. $! is the PID of the last process run in the background and $$ is the PID of the script itself. You might use the latter to create more-or-less unique lockfile names (time stamp is probably better for that, actually). Still, they may come in useful as your script matures.

look into 'man fuser' - no need for lockfiles or ps-ing.

Hi all,

Will this work if i keep it in my crontab, please see if any syntax error is there.

#!/bin/ksh

while [ true ]; do

       for i=$\(ps -ef | grep SCRIPT_NAME |grep -v grep |wc -l\)

        if [ "$i" -lt 1 ]

        then

        echo "\`date '\+%Y%m%d|%H%M%S'\` Script Already running!!!"

  exit 0

while [ true ]; do

        i=$\(ps -ef | grep PROCESS_NAME |grep -v grep |wc -l\)

        if [ "$i" -lt 2 ]

        then

        echo "\`date '\+%Y%m%d|%H%M%S'\` WARNING !!! PROCESS IS DOWN"

        else

        echo "\`date '\+%Y%m%d|%H%M%S'\` PROCESS IS RUNNING"

        fi

done