#!/usr/bin/perl use strict; # make it impossible to run this script more than once at a time use Cron::AvoidMultipleRuns; print "Running... pid = $$\n"; # pretend this script actually does something here... sleep 20; #### package Cron::AvoidMultipleRuns; use strict; my $cleanup; INIT { $cleanup = 0; (my $pid_file = "$0.pid") =~ s/\.pl//; if ( -e $pid_file ) { open my $fh, '<', $pid_file or die "Can't open $pid_file for reading: $!\n"; my $line = <$fh>; my (undef, $pid) = split(/\s+/, $line); if ($pid) { print "Found a pid file: pid = $pid.\n"; my $status = kill(0, $pid); if ($status) { print "old job is still running.\n"; exit; } else { print "The old job is no longer running.\n"; } } } open my $fh, '>', $pid_file or die "Can't open $pid_file for writing: $!\n"; flock ($fh, 2) or die "can't obtain exclusive lock on file $pid_file: $!\n"; print $fh "pid: ", $$, "\n"; close $fh; $cleanup = 1; } END { (my $pid_file = "$0.pid") =~ s/\.pl//; if ( -e $pid_file && $cleanup ) { unlink $pid_file or die "can't unlink $pid_file : $! \n"; } } 1;