package Cron::AvoidMultipleRuns; use strict; use warnings; use Cwd qw( realpath ); use Errno qw( EWOULDBLOCK ); use Fcntl qw( LOCK_EX LOCK_NB ); use File::Spec::Functions qw( rel2abs ); my $lock_file; my $lock_fh; { $lock_file = realpath(rel2abs($0)) . '.lock'; open($lock_fh, '+>>', $lock_file) or die("Can't create lock file \"$lock_file\": $!\n"); if (!flock($lock_fh, LOCK_EX|LOCK_NB)) { undef $lock_fh; if ($! == ($^O =~ /Win32/ ? 33 : EWOULDBLOCK)) { die("Another instance of this program is running. Exiting.\n"); } else { die("Cannot lock lock file \"$lock_file\": $!\n"); } } } END { if (defined($lock_fh)) { undef $lock_fh; # Release lock unlink($lock_file) ;#or warn("Can't unlink lock file \"$lock_file\": $!\n"); } } 1;