Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

(Ovid) Re: semaphores

by Ovid (Cardinal)
on Mar 18, 2002 at 22:08 UTC ( [id://152597]=note: print w/replies, xml ) Need Help??


in reply to how to use semaphores?

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://152597]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-24 02:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found