#!/usr/local/bin/perl

use Fcntl ':flock'; 

$plane="plane_reserve";
$hotel="hotel_reserve";

my $user = $ARGV[0];

open(HOTEL,"+<$hotel") || die("$$ $user can't open $plane\n");
flock(HOTEL,LOCK_EX);
# sleep 1;
&reserve('HOTEL',$hotel);

open(PLANE,"+<$plane") || die("$$ $user can't open $plane\n");

flock(PLANE,LOCK_EX);
# sleep 1;
&reserve('PLANE',$plane);

# flock(HOTEL,LOCK_UN);
close(PLANE);   # and release lock
close(HOTEL);   # and release lock

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