use strict; use warnings; use Fcntl ':flock'; # import LOCK_* constants warn "program starts\n"; my $somelockfile = 'choosealockfilename'; # adjust according to your needs open(my $fhlock, '>', $somelockfile) or die "Error: open '$somelockfile': $!"; warn "before flock: filename='$somelockfile'\n"; # Note: process will block at this point until the lock is acquired. flock($fhlock, LOCK_EX) or die "Error: flock '$somelockfile': $!"; # Lock is now held until $fhlock is closed. # Note that even if this program crashes or is killed, $fhlock will # be closed by the OS and the lock released. # ... warn "Got lock, sleeping for 10 secs...\n"; sleep 10; warn "woke up\n"; # Release the lock simply by closing the file handle. close $fhlock or die "Error: close '$somelockfile': $!"; warn "lock released: sleeping for 5 secs...\n"; sleep 5; warn "program ends\n";