Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Prevent a script from running twice

Status
Not open for further replies.

gregor weertman

Programmer
Sep 29, 2000
195
NL
I have this problem.

I want to be sure a script will not start twice.

The method I use now is:
pattr="sh.-c|vi|tail|view|grep|$$"
running=`ps -ef |grep ./program.sh |egrep -vic "$pattr"`
if [ "$running" -ne 0 ]
then
echo already running.
exit
fi

This is not watertight.
When the system has not enough recourses the script will start twice.



I can also use a lockfile.
I can write the pid in it
When the file exists, search for the pid, when not there start.
When the file not exists start
When running and file removed stop


Is there a better way?

How did unix solve this.
What system prevents me from starting cron twice.

Regards Gregor.
Gregor.Weertman@mailcity.com
 
I am not totally sure I understand your requirement. You could run the script from the /etc/inittab file with a 'once' option. It will only start once on bootup.
 
A problem with lock files is you can get race conditions. Two processes could start up (almost) simultaneously and both not see a lock file.

Another solution is &quot;fuser <filename>&quot; which I'm not sure is available for all Unixes, but it will tell you the processes that have the file open (reading, writing, running). You could have the script &quot;fuser&quot; itself and check that only one process is accessing the script. One problem with this method is someone may be running &quot;cat <script>&quot; and fuser will show this . So you might have to check the processes that &quot;fuser&quot; returns and make sure they are indeed running the script.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top