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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.