#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11148582 use warnings; use Time::HiRes qw( sleep ); sub grabthelockorexit { my $lockfilename = '/tmp/d.11148582.lockfile'; # FIXME to your filename open our $fh, '>>', $lockfilename or die "$! on $lockfilename"; use Fcntl qw(:flock); flock $fh, LOCK_EX | LOCK_NB or die "$$ exiting $!\n"; } # The following is just test code for (1 .. 9) { if( my $pid = fork ) { sleep 0.33; } elsif( defined $pid ) { sleep 0.1 + rand( 0.1 ); grabthelockorexit(); print "$$ got lock\n"; sleep 1; # FIXME body of code... print "$$ exiting\n"; exit; } else { die "fork failed" } } 1 while wait > 0; # wait until all children finish