Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (9)
As of 2024-03-19 08:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found