use Fcntl 'LOCK_EX'; =head2 C Pass C a file name and will will add a .sem extension, open the semaphore (creating if necessary), and get an exclusive lock on the file. The function returns a file handle that should be passed to sem_unlock() to unlock the file. If the program terminates, the file will be unlocked automatically. =cut sub sem_lock { my $sem_file = shift || die "No file specified"; $sem_file .= '.sem'; open my $fh, ">", $sem_file or die "Cannot open semaphore $sem_file: $!"; flock $fh, LOCK_EX or die "Cannot get exclusive lock on $sem_file: $!"; return $fh; } =head2 C Pass C a file handle and it will close it. It returns true or false depending on success or failure. It doesn't I the file as this happens automatically when a file is closed. This function is primarily just to complement C. =cut sub sem_unlock { my $fh = shift; close $fh or return 0; return 1; }