------------------------------------------------------------------------------- Locking... For more locking info please see C/locking.hints ------------------------------------------------------------------------------- Per File Locking... WARNING: the file must be opened for write or append for write locks to work correctly! This is especially the case for Solaris 9 where shared locks are the same as exclusive locks, AND the file MUST be writable even if you never write to it! If it isn't writable you get a "Bad file number" Error. Example code.... #!/usr/bin/perl # # Using flock(), this uses the systems broadest locking mechnism available use Fcntl qw{:DEFAULT :flock}; sub lock { local(*FILE) = @_; flock(*FILE, LOCK_EX | LOCK_NB ) or do { warn "$prog: File is locked -- continuing lock attempt...\n"; flock(*FILE, $lock_types{$type} ) or die ("$prog: Flock failure: $!\n"); }; } sub unlock { # not really needed if file closes flock(*FILE, LOCK_UN); } # ---- Example Use ---- (my $prog = $0) =~ s/^.*\///; system("touch /tmp/t"); print "opening...\n"; open(TEST, ">>/tmp/t") || die "cant open file \"/tmp/t\" for write"; print "locking...\n"; &lock(TEST); # lock file for writing print "locked\n"; sleep(10); # sleep for 10 seconds print "unlocking...\n"; &unlock(TEST); # unlock file print "closing...\n"; close(TEST); ------------------------------------------------------------------------------- Lock File Locking (via file creation) Using a standard lock file (non-root) See also file locking in shell/file.hints and C/C.hints Particularly for the more standard lock file methods NOTE: this is not atomic in NFS v2 but is in NFS v3 Perl 5 use Fcntl; # get the open flags sub lock($) { # create a file lock my ($file) = @_; until ( sysopen( LOCK, $file, O_RDONLY|O_CREAT|O_EXCL, 0444 ) ) { sleep 1; } } See the Perl4 sysopen() subroutine replacement in "perl_file.hints" Alturnativally you can use the simple procmail lockfile program to do all the hard work... system('/opt/bin/lockfile' $lockfile); ... unlink $lockfile; What is atomic is rename or linking a file! That is create a unique file for your process and try to rename() or link() it to the lockfile name. -------------------------------------------------------------------------------