in reply to Re: Order of flock and open
in thread Order of flock and open

If you're opening a file for destructive write, you have a bigger problem. Opening destroys the file, but you can't lock the file until you open it. One solution to this is to lock a different file, as someone else described. Another solution is to open the file twice: open it once for reading, lock it, and then open it for writing once you know you have the lock. As long as you keep the first filehandle open, you'll keep the lock.
You keep the lock on the now dead file, but you have a new file that exists but might not yet be fully written. And someone can come along and flock that! Now there are two flocks active. Repeat ad-nauseum, and you get an infinite number of flocks.

So, no, that's not the way to do it. Others have posted the proper way. Just wanted to point out that yours is flawed, so erase that part of your brain please. {grin}

-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.

Replies are listed 'Best First'.
Re: •Re: Re: Order of flock and open
by ferrency (Deacon) on Apr 30, 2003 at 20:20 UTC
    My experiences are probably platform-dependant on FreeBSD. However, those experiences offer empirical evidence that on my preferred platform, opening the file for write a second time opens the same file, not a new file, and subsequent lock attempts on the write filehandle fail.

    Example:

    % perl -MFcntl -e 'open my $f, "<foofile"; flock $f, LOCK_EX; open my +$g, ">foofile"; flock $g, LOCK_EX|LOCK_NB or die "No lock\n";' + No lock %
    In summary: please don't follow my original advice. Merlyn is probably right in the general case, and will probably even find a good explanation as to why I've fooled myself into believing what I do. I'll add a caveat to the particular portion of my brain which holds this information, but I'm unlikely to erase it completely :)

    Alan