my $lock = get_lock(); # --- critical stuff --- release_lock( $lock ); sub get_lock { my $server = shift || "localhost"; my $port = shift || 10101; my $retry_count = 0; my $lock; #sometimes the port needs a second, so we let it retry. while ( $retry_count++ < 30 ) { if( $lock = IO::Socket::INET->new(Proto => "tcp", PeerAddr => $server, PeerPort => $port) ) { $lock->autoflush(1); last; } } print $lock "\n"; until ( <$lock> ) { sleep(1) } return $lock; } sub release_lock { my $lock = shift || return; return close $lock; }