in reply to The internals of flock()

What you don't seem to realize is that flock blocks. That is, if you call it at a point when it cannot get a lock for normal reasons (ie the file is already locked by someone else), it will wait indefinitely. Your program will be stuck at the flock and won't continue executing until it has obtained the lock. When it continues, you will always have a lock.

Except if something very strange happened, in which case it is good to die noisily at that point because that is a clear indicator that something is very wrong with the system. You're not likely to be able to function properly aftewards anyway.

You can make flock nonblocking by adding a flag to the function call. However, this is only useful in specific circumstances. You shouldn't try it unless you understand why it is necessary.

And a sidenote: please use Fcntl; and write your flock calls using constants. flock(FILE, LOCK_SH); is much clearer than flock(FILE, 1);. Also, you may want to look up the difference between LOCK_SH and LOCK_EX; it's important to know of the existance of both and to understand when to use which.

Replies are listed 'Best First'.
Re: Re: The internals of flock()
by termix (Beadle) on Dec 26, 2001 at 03:06 UTC

    True and good advise.

    The programmer can also use time outs and alarms to walk out of a blocked IO call. Examples of this exist in the perlipc documentation (man perlipc ; perldoc perlipc). (might only work safely on UNIX though).

    This will solve your retry problem too. On failing a blocking IO operation, the cautious always pause before trying again. Also be careful of the advisory nature of the flock. A program is not forced to wait unless they lock and unlock voluntarily at the correct place in their operations.
    -- termix