my $lock_file = "./LockFile"; ## Put this in a common place GetLock: if ( ! -e $lock_file ) ## No Process is working { open ( my $lock, ">", $lock_file ) or die "Can't open $! "; if ( flock ( $lock, LOCK_EX | LOCK_NB ) ) { print $lock "$$\n"; close $lock; ## Now, you need to make sure your the process with the lock open ( $lock, "<", $lock_file ) or die "Can't open $! "; if ( flock ( $lock, LOCK_SH ) ) { my $pid = < $lock >; chomp ( $pid ); close $lock; if ( $pid eq "$$" ) { last; } ## Good--you have the lock else { redo GetLock; } } else { redo GetLock; } } else { ## Another process has the exclusive lock close $lock; usleep 1_000; ## wait .001 seconds redo GetLock; } } elsif { if ( -s $lock_file ) ## Another Process is already working { open ( my $lock, "<", $lock_file ) or die "Can't open $! "; my $who = < $lock >; chomp ( $who ); close $lock; ## Now you can stat the file and if it exists longer than ## some number of seconds/minutes, you have the pid to kill it. } else { redo GetLock; } } ## Put your testing and cache here.