... my $dotlockfile = $lockfile . '.lock'; my $lfh; # create the .lock with O_EXCL (Fail if the file already exists) while (!sysopen($lfh, $dotlockfile, O_RDWR|O_CREAT|O_EXCL)) { # some timeout checking code to get out this loop ... # wait for the existing .lock to go away sleep(1); } die "Can't create $dotlockfile" unless $lfh; close($lfh); # we got our own .lock, now continue with your lock code # no need to flock here my $number_of_clients = 0; sysopen(LOCKFILE,$lockfile,O_RDWR|O_CREAT) # create if necessary or die "Can not open/create $lockfile ($!)"; eval { $number_of_clients=||0; chomp($number_of_clients); seek(LOCKFILE,0,0) or die "Rewind error on $lockfile ($!)"; truncate(LOCKFILE,0) or die "Truncate error on $lockfile ($!)"; if($operation='checkin') { ++$number_of_clients; ... } else { ... --$number_of_clients; } print LOCKFILE $number_of_clients,"\n"; } if($@) { warn "Exception: $@"; } close(LOCKFILE) or warn "Error closing $lockfile ($!)"; # delete if necessary (our .lock will keep others at bay) if ($number_of_clients <= 0) { unlink($lockfile) or die "Unlink error on $lockfile ($!)"; } # now release our .lock unlink($dotlockfile) or die "Unlink error on $dotlockfile ($!)";