in reply to Lock File
For proper locking you can use flock :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"
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.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);
|
---|