in reply to Re^4: Writing to a log file without colliding
in thread Writing to a log file without colliding

Open for append + syswrite seems to work perfectly on Win32. Running the following code with an initial arg of 10, sets 10 copies of the code all writing to the same file. When they complete, a quick sort shows that every line, from each process, is in the file and uncorrupted.

It seems that specifiying append mode, not only does an initial seek to the end, but also ensures that each time a write is done, a seek-to-end is done implicitly also. (Or maybe my testcase is crap?).

#! perl -slw use strict; ## Decide a sync point if first instance ## or use the supplied sync time otherwise my $time = $ARGV[ 1 ] || time() +2 ; ## Ensure "recursion" stops. $ARGV[ 0 ]--; ## "Recursively" start asynchronous copies of ourself. system qq[start cmd /c $0 $ARGV[ 0 ] $time ] if $ARGV[ 0 ] > 0; ## Wait until sync time to give other copies a chance to get going. select undef, undef, undef, 0.1 until time() > $time; for( 1 .. 1000 ) { open FH, '>> :raw', 'data/append.tst' or die $!; syswrite FH, "$$\t$_\n"; close FH; ## Slow things a little so that the don't all comeout together. select undef, undef, undef, 0.001; }

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

Replies are listed 'Best First'.
Re^6: Writing to a log file without colliding (Win32 >> race)
by tye (Sage) on Aug 17, 2004 at 13:38 UTC

    There is a race condition in append mode in Win32. Your test case must just not race fast enough / close enough. BTW, binmode reduces the window size for the race.

    - tye        

      Indeed, you are correct. That's a shame, it would have been useful to me.

      Removing the delay and upping the line count to 10,000 eventually showed some corruption creeping in.

      With regard to the binmode, I was under the impression that ':raw' was equivalent to it. Especially inconjuction with syswrite?


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon