On Sat, Jul 28, 2001 at 04:15:33PM -0500, [EMAIL PROTECTED] wrote:
> #!/usr/local/bin/perl
>
> #use strict;
> use warnings;
>
> my $file = 'data';
> my $TIMEOUT = 10;
> sub LOCK_SH { 1 };
> sub LOCK_EX { 2 };
> sub LOCK_UN { 8 };
Do not manually define these constants. It will work, but it's better to
use Fcntl for them.
use Fcntl qw(LOCK_SH LOCK_EX LOCK_UN);
> sub filelock ($$) {
> my $path = shift;
> my $for_writing = shift;
You should probably localize FH around here, just in case you open a handle
named FH elsewhere:
local *FH;
That, or use IO::File.
> my ($lock_type,$path_name,$description);
> if ($for_writing) {
> $lock_type = LOCK_EX;
> $path_name = ">>$path";
> $description = 'writing';
> } else {
> $lock_type = LOCK_SH;
> $path_name = $path;
> $lock_type = LOCK_SH;
> $path_name = $path;
Why the double sets of assignment?
> $description = 'reading';
> }
>
> my ($msg,$oldsig);
> my $handler = sub { $msg='timed out'; $SIG{ALRM}=$oldsig; };
> ($oldsig,$SIG{ALRM}) = ($SIG{ALRM},$handler);
> alarm($TIMEOUT);
>
> open (FH,$path_name) or
> warn("Couldn't open $path for $description: $!"), return undef;
>
> # now try to lock it
> unless (flock (FH,$lock_type)) {
> warn("Couldn't get lock for $description (" . ($msg || "$!") . ")");
> alarm(0);
> close FH;
> return undef;
> close FH;
> return undef;
Here you have another set of doubled statements.
> }
>
> alarm(0);
Using alarm is one way of doing this, but signals aren't safe, so they
should be avoided when they can. Using flock(FH, LOCK_EX|LOCK_NB) in a
loop, with a tries counter and a maximum you won't go above, will give
you approximately the same thing.
> return FH; # error from perl -cw is: Bareword "FH" not allowed while
> # "strict subs" in use at sample line 47.
return \*FH;
> }
>
> sub fileunlock {
> my $fh = shift;
> flock($fh,LOCK_UN);
> close $fh;
> }
>
> my $fh = &filelock($file,1);
>
> print $fh "testing\n";
>
> &fileunlock($fh);
Michael
--
Administrator www.shoebox.net
Programmer, System Administrator www.gallanttech.com
--
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]