#!/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);