Dear List
I have written two identically same program, both of which using a same file
to write some data.My logic is that when prog1 will write data to the file
first it will lock the file , in between  the 2nd program will also try to
write data to that file if( which must happen) it gets the file has been
locked it will wait until the lock has been released , then again it will
open the file lock it and write data. Both the programs will running in
while( ) loop.

my code is as follows
*prog1.
*use strict;
use warnings;
use Fcntl qw(:flock);

my $lock_file="/home/bighosh/OraOneLoader_3.0.2/Source/flocktest.txt";
open LOCKFILE, ">>$lock_file" or die "Cannot open $lock_file $!";

while( )
{
unless (flock LOCKFILE, LOCK_EX|LOCK_NB) {
warn "File $lock_file already locked; waiting...\n";
#local $| = 1;
sleep 15;
print "Waiting for lock on filename...$lock_file\n";
flock(LOCKFILE, LOCK_EX) or die  $!;
}
print LOCKFILE "file locked, from location 1\n";
sleep 9;
print LOCKFILE "releasing lock from location 1\n";
close LOCKFILE or die "Cannot close $lock_file $!";
}
*
prog2
*use strict;
use warnings;
use Fcntl qw(:flock);

my $lock_file="/home/bighosh/OraOneLoader_3.0.2/Source/flocktest.txt";
open LOCKFILE, ">>$lock_file" or die "Cannot open $lock_file $!";
while( )
{
unless (flock LOCKFILE, LOCK_NB) {
warn "File $lock_file already locked; waiting...\n";
#local $| = 1;
print "Waiting for lock on filename...$lock_file\n";
sleep 19;
flock(LOCKFILE, LOCK_EX) or die  $!;
}

print LOCKFILE "file locked, from location 2\n";
sleep 5;
print LOCKFILE "releasing lock from location 2\n";
close LOCKFILE or die "Cannot close $lock_file";
}*
*
But when I am running the two programs but I am always getting the following
error from prog1

flock() on closed filehandle LOCKFILE at test.pl line 9.
File /home/bighosh/OraOneLoader_3.0.2/Source/flocktest.txt already locked;
waiting...
Waiting for lock on
filename.../home/bighosh/OraOneLoader_3.0.2/Source/flocktest.txt
flock() on closed filehandle LOCKFILE at test.pl line 14.
Bad file descriptor at test.pl line 14.

And the following error from prog1

flock() on closed filehandle LOCKFILE at test.pl line 10.
File /home/bighosh/OraOneLoader_3.0.2/Source/flocktest.txt already locked;
waiting...
Waiting for lock on
filename.../home/bighosh/OraOneLoader_3.0.2/Source/flocktest.txt
flock() on closed filehandle LOCKFILE at test.pl line 15.
Bad file descriptor at test.pl line 15.


Where I am making the mistake? One more thing if I want that when the
program will try to open the file and lock it will create a child process
which will do all the work and the control will go outside the while loop
and program will do rest of the jobs.

Thanks & Regards in advance
Anirban Adhikary.

Reply via email to