#!/usr/local/bin/perl

# usage    
#    echo 1 > plane.txt
#    echo 1 > hotel.txt
#    perl flock_test.pl plane.txt hotel.txt
#    perl flock_test.pl plane.txt hotel.txt


use Fcntl ':flock'; 

$plane=$ARGV[0];
$hotel=$ARGV[1];

open(PLANE,"+<",$plane) or die("$$ can't open $plane\n");
open(HOTEL,"+<",$hotel) or die("$$ can't open $plane\n");

flock(PLANE,LOCK_EX);
sleep 1;
&reserve('PLANE',$plane);
flock(HOTEL,LOCK_EX);
sleep 1;
&reserve('HOTEL',$hotel);
# flock(HOTEL,LOCK_UN);
close(HOTEL);   # and release lock
close(PLANE);   # and release lock
print "$$ hotel and plane resevred\n";

sub reserve {
    my ($fh,$file)=@_;
    if(($value = <$fh>)>0) {
	seek($fh, 0, 0);
	print $fh $value-1,"\n";
	print "$file reserved\n";
	return 1;
    } else {
	die("$$ can't reserve $file\n");
    }
}
