On Fri, Nov 28, 2008 at 00:09, Anirban Adhikary
<[EMAIL PROTECTED]> wrote:
snip
> 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 $!";
> }
snip

You open LOCKFILE outside the loop
inside the loop you
    attempt to lock the LOCKFILE
    you sleep for 9 seconds
    you close the LOCKFILE (without removing the lock I would note)

The second time through the loop LOCKFILE will not be open, and
therefore you will get "Bad file descriptor at test.pl line 15."  You
should also give strong consideration to indenting your code to make
it easier to read.  From your code it looks like you are trying to
write a test of locking.  Here is how I would write it


#!/usr/bin/perl

use strict;
use warnings;
use Fcntl qw(:flock);

die "usage: $0 lockfile location" unless @ARGV == 2;

my ($file, $loc) = @ARGV;

for (1 .. 20) {
        open my $fh, ">>", $file
                or die "Cannot open $file: $!";

        until (flock $fh, LOCK_EX|LOCK_NB) {
                print "at location $loc: $file already locked; waiting...\n";
                sleep 1;
        }
        print $fh "file locked, from location $loc\n";
        sleep 4;
        print $fh "releasing lock from location $loc\n";
        flock($fh, LOCK_UN);
        sleep 1; #give other program a chance to get a lock
}

I would then run

./testlock.pl 1 &
./testlock.pl 2 &

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to