Preventing Another Instance of A Program Running in Linux

The code below is my solution for preventing a program from running more than once at the same time in Linux.
The scenario: Consider if you have a cron job (jobA.sh) set to run at 6PM, 7PM, and 8PM.
While the 1st instance of jobA.sh started, it might (or might not) need more than an hour to finish. If it does requires more than one hour, while the 1st instance is still running, a 2nd instance of jobA.sh started.
Now you ended up with two instances of a same program consuming your CPU, files, etc – which will slow things down even more.

So here how I solve it:
When the 1st instance is started, check if there is a temporary lock file, if yes then just exits or quit. If not create the temporary lock file. And do your code/algorithm. After it finishes delete this lock file. When the 2nd instance started it will also do the same thing, checking if there is lock file.
It will be wise to put another cron job that cleans all lock file every 00:00AM. Just to be sure the next execution (at 6PM tomorrow) will be able to run

Since I’m no bash expert, let me know if there is a better way to do this. Cheers!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
# =================================
# author: Ronald Pringadi
# sleep command is in seconds
# =================================
vLockFile=/tmp/lockfile1.lock
echo 'start'
# If lockfile does not exist do the followings
if [ ! -f $vLockFile ]; then
    touch $vLockFile
    echo "Lock file doesn't exists, executing code"
    sleep 7 # this can be your big process that takes longer than an hour, but just for proof of concept, I use 7 seconds
    rm $vLockFile
else
    echo "Lock file exists do nothing"
fi
echo 'done'
This entry was posted in Linux, Operating System. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


6 + one =