Your code is subject to race conditions. Given two processes P1 and P2 started at the same time, you could end up with this behaviour where both processes execute the exclusive section "more code" at the same time :
P1 check if "the.lock" exists -> no P2 check if "the.lock" exists -> no P1 create "the.lock" -> ok P2 create "the.lock" -> ok P1 do "more code" P2 do "more code"
For proper locking you can use flock :
use Fcntl qw(:flock); open(LOCK, ">>", "lock") or die "Error: could not open or create lock: $!"; print "Waiting for lock...\n"; flock(LOCK, LOCK_EX) or die "Error: could not get lock"; print "Got lock!\n"; print "Working exclusively...\n"; sleep(10); print "Done.\n"; print "Release lock.\n"; flock(LOCK, LOCK_UN); print "Done.\n"; close(LOCK);
The "lock" file does not need to be erased at the end of the script, but you should open it in append mode '>>' rather than in truncate mode '>'. That way, if someone malicious pre-create a "lock" file as a symlink to another file, you won't erase the content of that linked file.

In reply to Re: Lock File by choocroot
in thread Lock File by toniax

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.