I have a script that I want to use only once. If the script call is called a second time, I check if the lock file exists. If the lock file exists, I want to check if the process is really running.
I worked with pgrep, but I do not get the expected results:
#!/bin/bash COUNT=$(pgrep $(basename $0) | wc -l) PSTREE=$(pgrep $(basename $0) ; pstree -p $$) echo "###" echo $COUNT echo $PSTREE echo "###" echo "$(basename $0) :" `pgrep -d, $(basename $0)` echo sleeping..... sleep 10
The results I get are as follows:
$ ./test.sh
I do not understand why I get "2" when only one process is running.
Any ideas? I am sure this is what I call it. I tried several different combinations and cannot figure out how to figure it out.
DECISION:
What I ended up doing this (part of my script):
function check_lockfile { # Check for previous lockfiles if [ -e $LOCKFILE ] then echo "Lockfile $LOCKFILE already exists. Checking to see if process is actually running...." >> $LOGFILE 2>&1 # is it running? if [ $(ps -elf | grep $(cat $LOCKFILE) | grep $(basename $0) | wc -l) -gt 0 ] then abort "ERROR! - Process is already running at PID: $(cat $LOCKFILE). Exitting..." else echo "Process is not running. Removing $LOCKFILE" >> $LOGFILE 2>&1 rm -f $LOCKFILE fi else echo "Lockfile $LOCKFILE does not exist." >> $LOGFILE 2>&1 fi } function create_lockfile { # Check for previous lockfile check_lockfile #Create lockfile with the contents of the PID echo "Creating lockfile with PID:" $$ >> $LOGFILE 2>&1 echo -n $$ > $LOCKFILE echo "" >> $LOGFILE 2>&1 } # Acquire lock file create_lockfile >> $LOGFILE 2>&1 \ || echo "ERROR! - Failed to acquire lock!"
jared source share