What is the best way to ensure only one copy of bash script is running (in BSD)?

I my freebsd 7.0 box, there is no "lockfile" command
Code:
$ lockfile
-bash: lockfile: command not found
therefore I can't use the lockfile approach.

So, what is the best way to ensure only one copy of bash script is running?
 
A really, really simple approach:
Code:
#!/bin/sh

if [ -f /var/run/somepid ]; then
 # Found a pid file
 ps -p `cat /var/run/somepid` > /dev/null
 if [ $? eq 0 ]; then
   # It's still running
   echo "Already running"
   exit
 fi
 # Stale pid file
 rm /var/run/somepid
fi
echo $$ > /var/run/somepid

# Do your stuff
 
SirDice said:
A really, really simple approach:
Code:
#!/bin/sh

if [ -f /var/run/somepid ]; then
 # Found a pid file
 ps -p `cat /var/run/somepid` > /dev/null
 if [ $? eq 0 ]; then
   # It's still running
   echo "Already running"
   exit
 fi
 # Stale pid file
 rm /var/run/somepid
fi
echo $$ > /var/run/somepid

# Do your stuff

Do I have to remove the pidfile (/var/run/somepid) at the end of my script?
 
Back
Top