in reply to Re: Flock Feedback
in thread Flock Feedback

If you just want a simple incrementing counter, one way to do this is to use the size of the file as the counter, rather than its contents. You don't need locking to do this:

my $filename = '/path/to/file'; # Increment the counter (atomically, so no locking required) open(FILE, ">> $filename") or warn "Missed a count"; print FILE '.' # Ouput one (arbitrary) byte close FILE; # What is the counter set to? my $countval = -s $filename || 0;

The disadvantage of this technique is that it uses one byte of disk space for each count.

Replies are listed 'Best First'.
Re: Re: Re: Flock Feedback
by chipmunk (Parson) on Feb 26, 2001 at 20:04 UTC
    Not only does this use one byte of disk space per count, which is ridiculously wasteful, but you still have a race condition if two processes try to write to the file and then check its size at the same time. Even with this approach you still would need locking.

      Even with this approach you still would need locking.

      Yes, as written. But the ">>" file mode does allow you to use something very similar to this without (additional) locking.

      use IO::Handle; my $filename = '/path/to/file'; # Increment the counter (atomically, so no locking required) open(FILE, ">> $filename") or warn "Missed a count"; FILE->autoflush(1); print FILE '.'; # Ouput one (arbitrary) byte my $counter= tell(FILE); close FILE;

      Now, if you reset your counters every so often, this can be a really nice little trick. To reset the counters, just do a unlink($filename) once a day/week/month, which also doesn't require any locking on your part! (Though the location and permissions on the counter file are a non-trivial problem so you may want to use sysopen so you can specify permission bits for the case when the file is recreated.)

              - tye (but my friends call me "Tye")