You are absolutely right -- you must watch out in this case. Most of the other replies don't bring up the fact that you must lock the entire process (read/write/rename). If you do this with a separate file, it is rather straightforard.

UPDATE: merlyn is right that the "code" below is fishy and should not be used. Take it as an example of what can go wrong if you try to get too tricky with locking. There are almost always conditions you will overlook (as I have.)

That said, I believe you can do this by locking both files, but you must pay attention to the order you perform the operations. You should be able to do the following in order...

open and lock the input file open lock the output file read the input file write the output file rename the input file rename the output file close both files (which unlocks them) delete old renamed input file

I'm not sure this works on all operating systems, but should work for Unix/Linux. You must use a non-blocking lock for the input file and you must close/reopen it in a loop if it is already locked. This is because someone can completely replace the input file before you get the lock for it and then your open file descriptor is pointing to the old stale (possibly deleted) input file. You should probably also use unique names (i.e. that don't collide with other processes) for the output file and the old input file.

This all seems rather complicated, which is why locking a separate file is much simpler. But, YMMV...

bluto


In reply to Re: Re: Order of flock and open by bluto
in thread Order of flock and open by svsingh

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.