use strict; use warnings; use Fcntl qw(:flock); my $lockfile = 'mylockfile'; sub BailOut { print "$0 is already running. Exiting.\n"; print "(File '$lockfile' is locked).\n"; exit(1); } print "start of program\n"; open(my $fhpid, '>', $lockfile) or die "error: open '$lockfile': $!"; flock($fhpid, LOCK_EX|LOCK_NB) or BailOut(); print "sleeping 15...\n"; sleep(15); print "end of program\n"; # Note: lock should be automatically released at end of program, # no matter how the process is terminated.