I have several parallel processes which access a critical region. I implement this region using a lockfile, which holds a counter (which I need for my app - it contains "the number of clients" using a certain part of the system). Inside the critical region, there occurs one of two operations: Checkin (which increments the counter) and checkout (which decrements the counter). My implementation so far is straightforward. Here a simplified version which shows the essential part:
This seems to work fine. But now comes a new twist: If (in the checkout case) the number of clients becomes zero, instead of writing 0 to the file, I would like to *delete* the lockfile. Now the problem is that it is not nice to delete a lockfile while it is still open, so I would have to do it *after* the close, don't I? But at that time, I don't own the lock anymore, so another process could have already acquired the file and incremented the number of clients.use Fcntl qw(:DEFAULT :flock); ... sysopen(LOCKFILE,$lockfile,O_RDWR|O_CREAT) # create if necessary or die "Can not open/create $lockfile ($!)"; flock(LOCKFILE, LOCK_EX) or die "Locking error on $lockfile ($!)"; eval { my $number_of_clients=<LOCKFILE>||0; chomp($number_of_clients); seek(LOCKFILE,0,0) or die "Rewind error on $lockfile ($!)"; truncate(LOCKFILE,0) or die "Truncate error on $lockfile ($!)" +; if($operation='checkin') { ++$number_of_clients; ... } else { ... --$number_of_clients; } print LOCKFILE $number_of_clients,"\n"; } if($@) { warn "Exception: $@"; } flock(LOCKFILE, LOCK_UN) or die "Unlocking error on $lockfile ($!) +"; close(LOCKFILE) or warn "Error closing $lockfile ($!)";
How can I solve this?
One more note: I know that my solution is flawed in that it would allow the number of clients to become negative (if checkout is called without a matching checking). I am aware of this, but this is something I can handle easily.
In reply to File Locking plus delete Lockfile question by rovf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |