Your code is subject to race conditions. Given two processes P1 and P2 started at the same time, you could end up with this behaviour where both processes execute the exclusive section "more code" at the same time :
P1 check if "the.lock" exists -> no
P2 check if "the.lock" exists -> no
P1 create "the.lock" -> ok
P2 create "the.lock" -> ok
P1 do "more code"
P2 do "more code"
For proper locking you can use flock :
use Fcntl qw(:flock);
open(LOCK, ">>", "lock")
or die "Error: could not open or create lock: $!";
print "Waiting for lock...\n";
flock(LOCK, LOCK_EX)
or die "Error: could not get lock";
print "Got lock!\n";
print "Working exclusively...\n";
sleep(10);
print "Done.\n";
print "Release lock.\n";
flock(LOCK, LOCK_UN);
print "Done.\n";
close(LOCK);
The "lock" file does not need to be erased at the end of the script, but you should open it in append mode '>>' rather than in truncate mode '>'. That way, if someone malicious pre-create a "lock" file as a symlink to another file, you won't erase the content of that linked file.
|