http://www.perlmonks.org?node_id=1009964


in reply to Re^2: Safe to open+close for every write, without locking?
in thread Safe to open+close for every write, without locking?

Here ya go:

#!/usr/bin/perl open my $fh, '>>', '/tmp/out' or die "open: $!\n"; sub output { my ($id) = @_; my $line = sprintf "[%02d: my id is: %02d]\n", $id, $id; # 19 char +s print $fh $line x 500; # bigger than 8K, and $line straddles boun +dary warn "$id: sleeping...\n"; sleep 1; warn "$id: exiting\n"; exit; } for (1..3) { sleep 1; warn "$_: spawning...\n"; my $pid = fork(); die "fork failed: $!\n" unless defined $pid; next if $pid; # child output($_); } sleep 5; __END__
And here's the output:
$ rm -f /tmp/out $ perl5160 /tmp/p1 1: spawning... 1: sleeping... 2: spawning... 1: exiting 2: sleeping... 3: spawning... 3: sleeping... 2: exiting 3: exiting $ grep -v '^\[..: my id is: ..]$' /tmp/out [02[03: my id is: 03] : my id is: 03] $

Dave.

Replies are listed 'Best First'.
Re^4: Safe to open+close for every write, without locking?
by sedusedan (Monk) on Dec 22, 2012 at 01:48 UTC

    Hi Dave,

    Thanks for writing the script. I added a seek($fh, 0, 2) before print $fh ... and it still manages to overlap.

    So, flock() it is.