top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How would you write a shell script and ensure that only one instance of the script may run for every user?

+1 vote
249 views
How would you write a shell script and ensure that only one instance of the script may run for every user?
posted Feb 18, 2016 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
LOCKFILE=/tmp/lock-`whoami`
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
    echo "Already running!"
    exit 1
fi
trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
echo $$ > ${LOCKFILE}

Start by determining a name for the lock file. In this case, the lock file is generated by suffixing a common name with the username of the current user.

Then, check if the lock file exists and if the PID contained within the lock file is running. If it is, exit with a message.

Create a trap to remove the lock file on a clean exit, or unclean exits (any exit with the signal INT or TERM).

Finally, if the script has not exited yet, create the lock file, and store the PID of the current process ($$) in it.

answer Feb 22, 2016 by Manikandan J
Similar Questions
0 votes

One of our script need run on first Saturday every month. We have following setup on cron job but it run every Saturday.

15 04 1-7 * 6 /xxx/monthlybk.sh

Any one know how to fix it?

0 votes

I have a shell script copyScript.sh present in my pendrive.
What i want is, Whenever i connect pendrive to my pc this script should be run automatically.

Is it possible?
If yes then how to achieve this?

...