Archive for the ‘Perl’ Category

How to force only one Unix Perl, Python or Ruby script to be running at a time.

Saturday, June 9th, 2007

Let’s say you have the script that is executed every minute via cron. Most likely you’ve tested it, whether it is executing in less than one minute or not, but have you tested it while your box CPU resources are consumed at 100% ? Have you tested it how long it will be executing when your system is swapping ?

What if it will be running longer than the scheduled time interval is ? Then you’re likely to hit CPU, memory, number of processes or other resource’s limits.

Such issues can happen, and if your scripts are not immune to such situations, they’ll act just like nails in your system’s coffin. Especially if they’re running with low priority ( like “nice -n 19 ./your_script.sh” for example ).

Securing scripts that way could also be needed, when more then one execution at a time could have bad influence on information consistency - it may be needed to have such executions atomic.

Here are some code examples of how the scripts could be secured. Those examples are showing the trick to lock the script file itself.

For Perl scripts :

#!/usr/bin/perl
use Fcntl qw(:flock);

open SELF, “< $0″ or die;

flock SELF, LOCK_EX | LOCK_NB or exit;

For Python scripts :

#!/usr/local/bin/python
import fcntl
import sys

f = open(sys.argv[0], ‘r+’)
try:
fcntl.flock(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)
except IOError:
sys.exit(0)

For Ruby scripts :

#!/usr/local/bin/ruby

f = File.open($0, File::RDONLY)
f.flock File::LOCK_EX | File::LOCK_NB or exit

Those snippets are showing the technique of creating exclusive lock on the script file itself. If another instance is trying to obtain that lock, it is not getting it and exits the execution. After the script quits, the lock is released.

You can just place similar code in the beginning of your script to not let it to run more than once at a time.



Entries (RSS) and Comments (RSS).


© 2007 Xadec.com. All rights reserved About Us | Contact Us | Terms of Use