On 2/17/06, Michael Moore <[EMAIL PROTECTED]> wrote:
> Hello shell script gurus. I'm sure I'm doing this the hard way...so if
> you could shed some light.

I'm not a guru but I have some ideas.  I realize this is a few days
old, but I havne't noticed the options I'm thinking of, so here goes.

Have you thought about using a scripting language? perl would be my
preference, but then that's kind of obvious. :>  That way you could
easily flock the pid file and reduce the possibility of the race
condition mentioned.

> I'm trying to write a shell script that will only run if it's not
> running already, and if it is running, kill the other process. ie:

#!/bin/bash

# If the program is already running then kill it and exit
# otherwise process normally.

SCRIPT=`basename $0`
PIDDIR=/var/run
PIDFILE=${PIDDIR}/${SCRIPT}.pid
CONTINUE=y

if [ -e ${PIDFILE} ]                   # Old process exists
then
  PID=`cat ${PIDFILE}`

  if [ -z ${PID} ] || [[ ! ${PID} =~ '^[0-9]*$' ]]
  then
    # something went wrong -- pid is empty or NaN
    # delete pidfile and continue normally
    echo Empty or corrupted pidfile, deleting, continuing ...
    rm ${PIDFILE}

  elif [[ ! ${PID} =~ '^[0-9]*$' ]]    # see if $PID is a number
  then
    RUNNING=`ps -p ${PID} -o pid=`     # see if it's running
    RUNNING=`ps -C ${SCRIPT} -o pid=`  # see if other instances are running

    for i in ${RUNNING}
    do
      kill -9 $i
    done

    echo Process was running, killed, exiting.
    rm ${PIDFILE}
    exit -1
  fi
fi

echo $$ > ${PIDFILE}

echo Normal processing here

rm ${PIDFILE}
exit 0
--
Alan

--------------------
BYU Unix Users Group
http://uug.byu.edu/

The opinions expressed in this message are the responsibility of their
author.  They are not endorsed by BYU, the BYU CS Department or BYU-UUG.
___________________________________________________________________
List Info: http://uug.byu.edu/cgi-bin/mailman/listinfo/uug-list

Reply via email to