Home

Search this site:
 

Horshack’s
very
own site

 

This is Bavaria, Germany!
You will find links to Perl,
bootdisks for system administration,
a lot of Linux,
Windows administration
and some personal belongings.
Locking files

Locking files

When you want a perl-script running only one time because there are ressources that can be used only one time (webcams, sensors) or you simply want to avoid crontab-scripts running a hundred times because they all are waiting for someting then you want to lock files.

The module Fcntl.pm only imports some system-constants into your namespace. The function flock itself is perl-core. You can use it in every perl-environment.

#!/usr/bin/perl
use strict;
use warnings;
use Fcntl qw/LOCK_EX LOCK_NB/;
use File::Basename;

my ( $lock_fh, $lock_fqn );

# Lockfile with the same name as the program itself
$lock_fqn = "/var/lock/" . basename($0);
open( $lock_fh, ">", $lock_fqn ) || die "Could not open $!";
unless ( flock( $lock_fh, LOCK_EX | LOCK_NB ) ) {
    die "Can't lock with file $lock_fqn, another process is locking";
}

# do something which should be done only once
# on this system
foreach ( 1 .. 10 ) {
    print "Wait $_/10\n";
    sleep 5;
}

# when the programm terminates, don't
# forget to close the lockfile
print "Closing logfile $lock_fqn\n";
close $lock_fh;
unlink $lock_fqn;
Impressum