I've written what's quickly becoming a hefty script and I need to implement file locking since it's a CGI that can be called multiple times - I haven't had it clobber a file yet but I'm gritting my teeth in morbid anticipation.

My question stems from the fact that every example of flock I've been able to find has called die when the lock fails.

My CGI script outputs pages all at once a la HTML::Template rather than piece by piece - if I die in the middle of the script, the user gets an ugly, ugly error message and not an HTML page. I don't want to do this under any circumstances.

Since die isn't an option I've set up the following:

if (sysopen(TRIGGERFILE, "$config->{xmlpath}trigfile.tf", O_WRONLY | O +_EXCL | O_CREAT)) { if (flock (TRIGGERFILE, LOCK_EX | LOCK_NB)) { print TRIGGERFILE "\n"; } else { push (@errors, qq(<p class="message">error message</p>)); } close TRIGGERFILE; } else { push (@errors, qq(<p class="message">error message</p>)); }

My question is about the close. If the lock fails, is the file still open? In other words, do I need a close statement after a failed lock or can I move it just below the statement that prints to the file?

Thanks again for your help, fellow monks.


In reply to Flock, die and statement order by Ionizor

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.