Try this:
use Fcntl ':flock'; sub alter_file { open(HANDLE1, ...); flock(HANDLE1, LOCK_EX) # exclusive lock or die "unable to obtain lock: $!"; chop; chop; chop; close(HANDLE); # also releases lock } sub process { open(HANDLE2, ...); flock(HANDLE2, LOCK_SH) # shared lock - allows multiple readers or die "unable to obtain shared lock: $!"; ...read from file... close(HANDLE2); # also releases lock }
Note: The flock call will block until the lock can be acquired.

Another approach which may work for you is to use an atomic operation to replace the contents of file:

sub alter_file { open(HANDLE1, ">/some/tmp/file"); ...write to HANDLE1... close(HANDLE1); rename("/some/tmp/file", "file"); }
In this case no call to flock is needed in the process subroutine. Other processes accessing file may not always get the latest version of the file, but once they open file the contents won't change on them.

In reply to Re: Two questions on interprocess communication by pc88mxer
in thread Two questions on interprocess communication by cypress

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.