Subjectively

dd if=/dev/random | kirk > blog

Subjectively header image 2

bash shell script to manage pid file creation/deletion

October 30th, 2009 · No Comments · Linux, OS X

Problem: You want your script to execute without overlapping another execution.
Solution: Make a flag file so you know that your script is already executing.
Extended problem: What if your script dies and leaves the flag file behind?
Extended solution: Check the process list to see if the old instance is still alive.
Ext. Ext. Problem: What if somebody kills my script?
Ext. Ext. Solution: Trap the abnormal exit and clean up properly.
Ext. Ext. Ext. Problem: What if someone else is invoking a script with exactly the same name as mine?
Ext. Ext. Ext. Solution: You’re screwed. Give your script a really long descriptive name so this won’t happen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#figure out where to put the pid file
myfile=`basename "$0" .sh`
whoiam=`whoami`
pidfile=/tmp/$myfile.pid
[[ "$whoiam" == "root" ]] && pidfile=/var/run/$myfile.pid
 
#remove the pid file cleanly on exit
function cleanup () {
  [[ -f "$pidfile" ]] && rm "$pidfile"
  #add other post processing cleanup here
}
 
# trap all the exit signals for cleanup
trap "cleanup; exit" 0 SIGINT SIGQUIT SIGTERM     # ON OS/X this is 0 2 3 15
 
# Am I already running?
[[ -f "$pidfile" ]] && {
  #pidfile exists, check if previous process exists.
  pid=`head -n 1 $pidfile`
  pidtest="\$1 == $pid { print \$7 }"
  procname=`ps awx | grep $0 | awk "$pidtest"`
  [[ "$procname" == "$0" ]] && {
    echo "Running"
    exit 1
  }
}
 
#put this pid in the file
echo $$ > "$pidfile"

Tags:

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment

You must log in to post a comment.