The logic is OK but you have created a possible infinite loop. sysopen may fail with the flags you have if the file exists but it may fail for other reasons ie Permissions. If you have a perms problem you code will loop forever burning 100% CPU in all liklihood. Here is a tempfile function we use that may be the sort of thing you are after. It returns the locked $fh and $filename (for unlinking or whatever) if it succeeds and limits the number of retries to less than infinity :-) Note File::Temp is a well tested solution and offers features not present in this function.

use Fcntl; # need constants O_CREAT | O_EXCL | O_RDWR sub get_tempfile { my ( $dir, $prefix, $max_tries ) = @_; $dir ||= '/tmp'; $prefix ||= 'temp'; $max_tries ||= 10; my @CHARS = ( 'A' .. 'Z', 'a' .. 'z', 0 .. 9, '_' ); ui_system_error( "$dir is not a directory" ) unless -d $dir; ui_system_error( "$dir is not writable" ) unless -w $dir; $dir =~ s!/$!!; my $fh; for ( 0 .. $max_tries ) { my $name = sprintf "$prefix-%d-", time(); $name .= $CHARS[ int( rand( $#CHARS ) ) ] for 1..10; my $path = "$dir/$name"; return ($fh, $name) if sysopen($fh, $path, O_CREAT | O_EXCL | O_ +RDWR, 0600); } ui_system_error( "Could not create unique filename after $max_trie +s" ); }

cheers

tachyon


In reply to Re: Avoiding race condition with sysopen by tachyon
in thread 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.