[boulder.pm] advisory locking
Walter Pienciak
walter at frii.com
Thu Jan 4 12:05:48 CST 2001
Quiet group.
Anyway, I thought I'd try to stir the pot here by posting some code,
which you may or may not find useful. Here's a small script I wrote that's
basically a wrapper around vi (or $EDITOR), which uses advisory locking
to make sure different people don't overwrite each others work by
editing the same file at the same time.
Walter
#!/opt/bin/perl -w
# nicevi -- to keep multiple people from editing the same file at
# the same time.
# Walter Pienciak <w.pienciak at ieee.org>
use Fcntl qw(:DEFAULT :flock);
if (scalar @ARGV == 0) {
print "Usage: $0 file1 [file2 file3 ...]\n";
exit 0;
}
my $LOCKDIR = '/var/tmp';
my $EDITOR = '/bin/vi'; # Default editor.
$EDITOR = $ENV{EDITOR} if ($ENV{EDITOR} ne ''); # But not everyone likes it.
my $file;
while (scalar @ARGV > 0) {
$file = shift;
&file_lock($file);
system("$EDITOR $file");
&file_unlock($file);
}
sub file_lock {
my $f = shift;
sysopen(LOCKFILE, "$LOCKDIR/LOCK_$f", O_WRONLY | O_CREAT)
or die "Can't open $LOCKDIR/LOCK_$f: $!";
flock(LOCKFILE, LOCK_EX|LOCK_NB) # Nonblocking lock.
or die "Can't obtain lock for $LOCKDIR/LOCK_$f: $!";
}
sub file_unlock {
my $f = shift;
unlink "$LOCKDIR/LOCK_$f"
or die "Can't delete $LOCKDIR/LOCK_$f: $!";
flock(LOCKFILE, LOCK_UN)
or die "Can't release lock for $LOCKDIR/LOCK_$f: $!";
}
## Th-th-that's all, folks!
More information about the Boulder-pm
mailing list