| 1 | =head1 NAME | ||
| 2 | |||
| 3 | DBfilelock - Class to encapsulate filelocking | ||
| 4 | |||
| 5 | =head1 SYNOPSIS | ||
| 6 | |||
| 7 | This class encapsulates filelocking. DO NOT USE IT since file locking | ||
| 8 | is bad and subject to race conditions. Use flock instead. | ||
| 9 | |||
| 10 | =head1 LICENSE | ||
| 11 | |||
| 12 | Copyright (C) 2002 Globewide Network Academy | ||
| 13 | Released under the SCHEME license see LICENSE.SCHEME.txt for details | ||
| 14 | |||
| 15 | =cut | ||
| 16 | |||
| 17 | |||
| 18 | package DBfilelock; | ||
| 19 | use IO::File; | ||
| 20 | |||
| 21 | sub new { | ||
| 22 | my $proto = shift; | ||
| 23 | my $class = ref($proto) || $proto; | ||
| 24 | my $self = {}; | ||
| 25 | ($self->{'FILENAME'}) = @_; | ||
| 26 | $self->{'ENDTIME'} = 20; | ||
| 27 | |||
| 28 | $self->{'FH'} = undef; | ||
| 29 | |||
| 30 | bless ($self, $class); | ||
| 31 | $self->set(); | ||
| 32 | return $self; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub set { | ||
| 36 | my ($self) = @_; | ||
| 37 | my ($release_time) = time + $self->{'ENDTIME'}; | ||
| 38 | while (-e $self->{'FILENAME'} && time < $release_time) { | ||
| 39 | sleep(1); | ||
| 40 | } | ||
| 41 | $self->{'FH'} = IO::File->new(">$self->{'FILENAME'}"); | ||
| 42 | if (!defined($self->{'FH'})) { | ||
| 43 | die "Cannot open lock file $self->{'FILENAME'}"; | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | sub release { | ||
| 48 | my ($self) = @_; | ||
| 49 | $self->{'FH'}->close(); | ||
| 50 | $self->{'FH'} = undef; | ||
| 51 | unlink($self->{'FILENAME'}); | ||
| 52 | } | ||
| 53 | |||
| 54 | 1; | ||
| 55 |