Hello, good Monks. I have a problem which I think I have solved, but I'd like to pass it by everybody to see if there's anything silly I overlooked. A question from earlier today (File opening/creating) -- along with Abigail-II's answer -- prompted me to think about possible race conditions in my own code.

Based on a small amount of research (and a bit of perusal of File::Temp's source), I have found a solution using sysopen which I think eliminates a previous race condition.

Here is my original code (simplified a bit to lay bare the algorithm):

my $outfile = "a"; $outfile++ while -e $outfile; open my $fh, ">", $outfile or die "$outfile: $!";

And here is the replacement I've come up with:

my $outfile = "a"; my $fh; $outfile++ until sysopen $fh, $outfile, O_WRONLY|O_CREAT|O_EXCL;

This code looks good to me, and it works. I have never before used sysopen, though, so I'm not sure if I've made any mistakes (e.g. with the sysopen flags), or if my approach is wrong-headed. Just in case it's not blindingly obvious, I'm trying to create a new file for output, with a sequentially increasing name, but without overwriting previous files. Any thoughts appreciated.

Update: just for clarification, I'm not seeking to make temporary files. If that were the case, I'd use File::Temp. Instead I'm after permanent files with unique and sequential file names.


In reply to Avoiding race condition with sysopen by revdiablo

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.