Question

Okay, so I have a script that contains an infinite loop that checks a postgres database. That works fine. In order to ensure that the process will continue to run I am using cron to continue to execute the file every minuet. To stop multiple instances of this I wrote this PID check script.

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

if [ -e ${PIDFILE} ]; then
    PID=`cat ${PIDFILE}`;

    echo "Found PID ${PID}"

    RUNNING=`ps -p ${PID} -o pid=`
    if [ ${RUNNING} -eq ${PID} ]; then
        RUNNINGNAME=`ps -p ${PID} -o command=`
        if [ `echo "${RUNNINGNAME}" | grep -c *${SCRIPTNAME}*` -eq "1" ]; then
            echo "${SCRIPTNAME} is already running."
            exit 1
        else
            echo "Wrong PID file."
        fi
    else
        echo "Outdated PID file."
    fi
else
    echo "No PID file."
fi
echo $$ > ${PIDFILE}

When I run the process with ./script.sh it will not let me run another instance in a different command line. But the issue is that when I initialize this in cron it will create multiple instances seemingly without regard for my pid check. Any help would be much appreciated.

Was it helpful?

Solution

By simply removing the section of code

if [ echo "${RUNNINGNAME}" | grep -c *${SCRIPTNAME}* -eq "1" ]; then
echo "${SCRIPTNAME} is already running." exit 1 fi

and replacing it with a simple exit 1 I was able to get it to work.

For some reason, cron does not like this part of the script. When running it manually, it is good to keep this as it will help in the eventuality that your script is actually the script that is running under the stored pid. This is a small chance and would generally only happen due to user error, but building for the possibility of this is a good Idea.

I am still unsure why this breaks in cron, but it does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top