in reply to Re^3: Fcntl() and multiple filehandles
in thread Fcntl() and multiple filehandles

I see two scenarios here. One is the one that Annonymous mentioned in his original post, the second is the typical problem of multiple processes. Both are quite valid concerns, but I believe they require two seperate solutions. If closing any file handle to a file clears all locks on it, the there's not much point in using shared locks within the same process. But using shared locks per fcntl can prevent two different processes from stepping on each other's toes. So go ahead and place the locks for the sake of preventing your other scripts from stepping on your toes, but also keep some kind of internal locking mechanism--it has been suggested that a simple hash with file->lock status pairs would do for this. But consider what happens if you have two handles/locks in one process and another process is waiting for an exclusive lock. When one of process A's handles is closed, it clears all of A's locks on the file and B starts working on it, even theough A's second handle is still open. To prevent this, the only solution I see is to be very careful within A in terms of how you design your code. Perhaps you need to keep an internal structure of some sort of filename->glob pairs so you always know when a hanlde is open and can pass the handle from sub to sub rather than needing to open a new handle.

Replies are listed 'Best First'.
Re^5: Fcntl() and multiple filehandles
by Anonymous Monk on Sep 21, 2004 at 12:52 UTC
    But using shared locks per fcntl can prevent two different processes from stepping on each other's toes.

    I think you've misunderstood--that's exactly what it does NOT do. If there are two filehandles open on a given file (regardless of whether they are opened by one process or two seperate processes), when one of them is closed, all locks are removed. So if process A and process B have shared locks on a file, as soon as A closes his handle, B loses his lock. If process C has two handles and two locks on another file, then both locks are cleared as soon as one handle is closed.
      Your first example should only be true if Processes A and B are related processes (parent-child or siblings) and the filehandle is exactly the same one---a parent process opened the file, left it open after a fork, and the child process is locking that handle. Your second example should only be true if Process C has multiple locks on the same region of the same file.

      If you're seeing different behavior than this, post a minimal example.