Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: What the flock!? Concurrency issues in file writing.

by massa (Hermit)
on Oct 01, 2008 at 16:55 UTC ( #714838=note: print w/replies, xml ) Need Help??

in reply to What the flock!? Concurrency issues in file writing.

Try this (works in some tests I did):
use strict; use warnings; sub report($@) { my $file = shift; my $temp = "$file.$$"; 1 until -w $file; rename $file, $temp or die "rename [$file] [$temp]: $!"; open my $t, '+<', $temp or die "open [$temp]: $!"; seek $t, 0, 2 or die "seek [$temp]: $!"; print $t @_; close $t; rename $temp, $file or die "rename [$temp] [$file]: $!" }
As the two 'rename' operations are atomic, this might work, and the file inode is preserved, so all should be well. Change the "$file.$$" for other (better) tempfilename if you expect concurrent accesses by the same process or thru the network.
[]s, HTH, Massa (κς,πμ,πλ)

Replies are listed 'Best First'.
Re^2: What the flock!? Concurrency issues in file writing.
by bluto (Curate) on Oct 01, 2008 at 17:02 UTC
    This won't work all of the time since there is a race condition. If two processes get past the 1 until -w $file line simultaneously. One will end up die'ing when the rename fails. Update: changed "while" to "until".

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://714838]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2021-12-04 10:38 GMT
Find Nodes?
    Voting Booth?
    R or B?

    Results (30 votes). Check out past polls.