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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |