Thursday, October 16, 2008

Directory locking in perl

Directory locking in perl can be achieved by using the file locking construct flock().In the below code, only one thread can access the files contained in the directory. Once the first thread is finished, then only the other thread can start reading the contents of the directory.

use Fcntl ':flock';
chdir('orders');
open( FILE_LOCK, ">file.lock");

#Get exclusive lock on a lock file.Waits till the lock is acquired
if (flock FILE_LOCK, LOCK_EX) {
opendir(DIR, '.');
@dir_contents = readdir(DIR);
#Sleep will help you test the code. Run the same code on two different shells
sleep(5);
foreach $file (@dir_contents){
print $file."\n";
}
sleep(5);
}
close FILE_LOCK;

No comments: