use strict; use warnings; use Fcntl ':flock'; # import LOCK_* constants open(my $fhlock, '>', $somelockfile) or die "Error: open '$somelockfile': $!"; # 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. # ... # Release the lock simply by closing the file handle. close $fhlock or die "Error: close '$somelockfile': $!";