in reply to sysopen vs. open

Hi,
something like

unless (-e $file) { open(FH,">", "$file") or die $!; }

is almost always wrong as it's open to race conditions.

See Perl Training Australia File test operators, the garden path of race conditions and PerlMonks Avoiding race condition with sysopen for more details.

So you're better off avoiding file tests:

use Fcntl; # Open $file for writing unless it already exists sysopen(FH, $file, O_WRONLY|O_EXCL|O_CREAT) or die $!;

HTH,
Thomas

Replies are listed 'Best First'.
Re^2: sysopen vs. open
by tilly (Archbishop) on May 15, 2009 at 15:25 UTC
    Why do you want to have a file that you know you just created? Most of the time when I want that I really want File::Temp. For locking you have other options available, including flock. You can complain that flock often doesn't work well over networked file systems. But sysopen also doesn't work well on those systems.

    So yes, there is a task that you can do with sysopen that you can't with open. But I have yet to encounter a situation where I thought that sysopen was the best option.