Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
I couldn't really decide where to put this, but I figured Meditations would be best.
I was working with a script yesterday and realized that flock() doesn't do much by itself.
Using a simple flock FILEHANDLE, LOCK_EX; won't always succeed in locking a file.
So, I created a subroutine that attempts to lock a file several times, and if it cannot, there is definitely something wrong, and the user is presented with an error.

So here is the small subroutine:

sub lockfile { my $file = pop(); for $i (1 .. 10) { sleep .15; $locked = 1 if (flock $file, LOCK_EX); } unless ($locked == 1) { print "\n\nFlock error: could not lock $file"; + exit; } }
There. Very easy subroutine that will try flocking a file 10 times before informing the user of an error.
I surprised myself by using pop()!
Anyway, this code is very easy to use:
lockfile (FILEHANDLE);

I could have also allowed an optional parameter that would allow the user to pass what kind of lock to use, rather than simply applying LOCK_EX, but I always use LOCK_EX, so...

Better not be an error in that post... ;-)

In reply to Flock Subroutine by mt2k

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?

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-06-15 19:57 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.