0

I have a backup script which sends my snapshots to a off-site location.

0 0 * * * /root/backup/backup_incremental >> /root/backup/test.log

For some reason my PID file which should stop the script form executing a second time doesn't work with cron. If I open two shells and start my script twice everything works as expected.

#!/usr/local/bin/zsh

PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin 
DATE=`date "+%Y-%m-%d_%H-%M-%S"` 

SCRIPTNAME=`basename $0`
PIDFILE=/var/run/${SCRIPTNAME}.pid


if [ -f ${PIDFILE} ]; then
       #verify if the process is actually still running under this pid
         OLDPID=`cat ${PIDFILE}`
         RESULT=`ps -ef | grep ${OLDPID} | grep ${SCRIPTNAME}`  

         if [ -n "${RESULT}" ]; then
             echo "${DATE}: Script already running (PID: ${OLDPID})! Exiting"
             exit 255
         fi

fi

#grab pid of this process and update the pid file with it
PID=`ps -ef | grep ${SCRIPTNAME} | head -n1 | awk ' {print $2;} '`
echo ${PID} > ${PIDFILE}

#send it
....


if [ -f ${PIDFILE} ]; then
    rm ${PIDFILE}
fi

This is my script striped down to the important bits.

So my question is how can cron start this more than once?

1
PID=`ps -ef | grep ${SCRIPTNAME} | head -n1 | awk ' {print $2;} '`

This could either return the PID of your script, or of the grep process, or of some unrelated process that happens to have a similar enough name. This is likely to be the cause of your problem: sometimes your script writes its own PID to the pidfile and sometimes it writes something else.

The PID of your script is in the variable $$.

For those cases when you actually need to find the PID of a process given its name, see Finding the ID of a process and killing it and grep - why do brackets in grep pattern remove the grep process from ps results?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.