User Tools

Site Tools


doc:appunti:prog:perl_flock

Locking di un file in Perl

#!/usr/bin/perl
 
use Fcntl ':flock';
 
# Try to open and lock the file.
open(FILE, "+< /path/to/file")
    || die('Error opening the file.');
 
# Try to lock the file, waiting 5 seconds max.
$i = 0;
while (! flock(FILE, LOCK_EX | LOCK_NB)) {
    if (++$i > 5) {
        close(FILE);
        die('Error locking the file.');
    }
    sleep(1);
}
 
# Now the file open and locked.
print "File is locked!\n";
sleep(20);
 
# Unlock and close the file.
flock(FILE, LOCK_UN);
close(FILE);
doc/appunti/prog/perl_flock.txt · Last modified: 2011/02/26 13:56 by niccolo