Acting on the assumption that you want to use semaphore files to lock and unlock files with Perl:
use Fcntl 'LOCK_EX'; =head2 C<sem_lock> Pass C<sem_lock> a file name and will will add a .sem extension, open +the semaphore (creating if necessary), and get an exclusive lock on the fi +le. The function returns a file handle that should be passed to sem_unlock() t +o unlock the file. If the program terminates, the file will be unlocked automa +tically. =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_fil +e: $!"; flock $fh, LOCK_EX or die "Cannot get exclusive lock on $ +sem_file: $!"; return $fh; } =head2 C<sem_unlock> Pass C<sem_unlock> a file handle and it will close it. It returns tru +e or false depending on success or failure. It doesn't I<unlock> the file as thi +s happens automatically when a file is closed. This function is primarily just +to complement C<sem_lock>. =cut sub sem_unlock { my $fh = shift; close $fh or return 0; return 1; }
Basically, with a given filename, sem_lock the filename and then use the file as normal. After you are done, sem_unlock the filehandle returned by sem_lock. There are variants of this you can use (such as creating a semaphore locking object and calling an unlock method).
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
In reply to (Ovid) Re: semaphores
by Ovid
in thread how to use semaphores?
by Ras
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |