in reply to Question about Flock and die

If you want flock to return immediately rather than wait for a lock to become free, you need a 'non-blocking' lock. eg:

flock LOCKFILE, LOCK_EX | LOCK_NB or die;

A trick I learned from Dominus is to open $0 for reading and lock it rather than creating a separate file for locking.

Replies are listed 'Best First'.
Re: Re: Question about Flock and die
by pg (Canon) on Apr 05, 2003 at 20:52 UTC
    Some little disagreement:-) (Overall, your answer is obviously correct, no doubt about that)

    1. Strictly speaking, locking $0 has no difference from locking a "separate" file, as $0 is still a separate lock file, not a direct lock on the file under concern itself.
    2. A caveat with this approach (to lock $0) is that, it adds a restriction that, in order to make the lock work, multiple users have to run a single copy of the script from the same location, which is not true all the time.
      locking $0 has no difference from locking a "separate" file

      Quite true, but my words were "creating a separate file" :-)

      Also, I was reading between the lines and (possibly incorrectly) came to the conclusion that the OP was trying to prevent simultaneous access to a script. If that was the goal but there were multiple copies of the script or mutliple names (links) then no, the $0 approach wouldn't work.