From: Francis Cianfrocca Date: 2006-08-14T11:46:29+09:00 Subject: Re: How do you use flock and clean up lock files? ------=_Part_170055_12577572.1155523586276 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 8/13/06, John Carter wrote: > > So I'm using flock, but I have this noxious race condition when I try to > clean up the lock files. > > I need a way of knowing if anything has a file open at the same time as > me, or I must always leave lock files lying around. Any suggestions? > > > Here is the sequence.. > Process A: fd = open( "lockfile", 'a') > Process A: flock(fd, LOCK_EX) > > Process A: do stuff in critical section... > > Process B : fd = open( "lockfile", 'a') > Process B: flock(fd, LOCK_EX) // Blocks waiting for lock > > Process A: Finishes, doesn't know about B, wants to clean up... > Process A: unlink fd > Process A: close(fd) > > Process B: Unblocks, B grabs lock. > > Process C : fd = open( "lockfile", 'a') // CREATES A NEW ONE! > Process C: flock(fd, LOCK_EX) // DOESN'T BLOCK! I think the unlink is your problem. In Unix when you unlink a file, it disappears from the filesystem, but any processes that have an open handle to the file will keep the file open until they close it. Any process that tries to then open a file with the same name will end up creating a new one. This happens in your example: process A creates and opens the lockfile, then B opens it, then A unlinks the file and closes its handle to it. At this point, the original file still exists (because B has it open and in fact also has an advisory lock on it), but it has been unlinked from the filesystem. So when C starts, it creates and locks a brand new file. The first file doesn't disappear completely until B closes its handle to it. Don't worry about leaving lock files around. If you really don't like it, put it in /tmp or /dev/shm. ------=_Part_170055_12577572.1155523586276--