in reply to Safe Counter

Hello Wise Monks! Here's the code I use to count. Somehow it resets to zero when 10 or more instances of it run at the same time. What's wrong with my code?

$completeadd = "counter.txt"; open(MFILE, "$completeadd") || die "file open failed: $!\n"; flock(MFILE, LOCK_EX) || die "Lock failed: $!"; @filedata1=<MFILE>; chomp @filedata1; close(MFILE); if ($filedata1[0]) { $filedata1[0]=$filedata1[0] + 1; } else { $filedata1[0] = 1; } open(MFILE, ">$completeadd") || die "file open failed: $!\n"; flock(MFILE, LOCK_EX) || die "Lock failed: $!"; print MFILE "$filedata1[0]"; close(MFILE);

Replies are listed 'Best First'.
•Re: Safe Counter Follow Up
by merlyn (Sage) on May 06, 2004 at 15:32 UTC
Re: Safe Counter Follow Up
by tachyon (Chancellor) on May 06, 2004 at 15:37 UTC

    What's wrong with my code?

    You have several race conditions. You open the file. You have yet to apply the lock. Then you lock it. You read it then CLOSE THE FILE RELEASING THE LOCK BUT YOU HAVE NOT FINISHED! You then do stuff ;-) While you are doing this stuff any other program can open and lock the file.

    There are many solutions but in essence you need a 'lock' that persists until you have completed the update. Ie LOCK, read, increment, write, UNLOCK. This is a rather well worn chestnut. Could I suggest Super Search Gotta go. I have a boarding call....

    cheers

    tachyon

Re: Safe Counter Follow Up
by Ovid (Cardinal) on May 06, 2004 at 15:33 UTC
Re: Safe Counter Follow Up
by Ven'Tatsu (Deacon) on May 06, 2004 at 16:59 UTC
    Take a look at the perlopentut man page (perlopentut on CPAN if perldoc is still down). Look in the section 'File Locking', there is example code for what you are trying to do.
Re: Safe Counter Follow Up
by Anonymous Monk on May 06, 2004 at 21:07 UTC

    You'll want something like this:

    #!/usr/bin/perl -w $| = 1; use strict; use Fcntl qw(:flock); my $count_file = 'counter.txt'; open( my $fh, '+<', $count_file ) or die( "open failed: $!" ); flock( $fh, LOCK_EX ) or die( "flock failed: $!" ); ++ ( my $count = <$fh> ); seek( $fh, 0, 0 ) or die( "seek failed: $!" ); truncate( $fh, 0 ) or die( "truncate failed: $!" ); print $fh $count; close( $fh ) or die( "close failed: $!" );