in reply to Fcntl() and multiple filehandles

Unfortunately, this is the required semantics of fcntl. To quote the POSIX specification: "All locks associated with a file for a given process shall be removed when a file descriptor for that file is closed by that process or the process holding that file descriptor terminates."

Everybody hates this, but it's necessary for backward compatibility. To quote the FreeBSD man page:

This interface follows the completely stupid semantics of System V and IEEE Std 1003.1-1988 (``POSIX.1'') that require that all locks associated with a file for a given process are removed when any file descriptor for that file is closed by that process. This semantic means that applica- tions must be aware of any files that a subroutine library may access. For example if an application for updating the password file locks the password file database while making the update, and then calls getpwnam(3) to retrieve a record, the lock will be lost because getpwnam(3) opens, reads, and closes the password database. The database close will release all locks that the process has associated with the database, even if the library routine never requested a lock on the data- base. Another minor semantic problem with this interface is that locks are not inherited by a child process created using the fork(2) system call.

Now, if your processes are the only ones locking this file (or files) and if they are all running on the same computer, you could use another file (that is not on NFS) for locking. I fear that your file is on NFS for a reason, though, which may mean that it is accessed from multiple computers.

Replies are listed 'Best First'.
Re^2: Fcntl() and multiple filehandles
by TedPride (Priest) on Sep 21, 2004 at 00:08 UTC
    Unless you really have to have simultaneous access for multiple scripts or instances of your script, you should be able to make do by checking for lock file, and if it's there, sleeping for a second and checking again, rinse and repeat. If the lock file isn't gone after x number of iterations, and if the lock file is the same one that was there when you started iterating, you can assume that the script that locked it died or hung up, and ignore / delete the lock and create your own.

    WWWBoard comes with file lock routines - you can always look at these and use them as the basis for writing your own lock / unlock routines.

      Hmmm...but what's to lock the lock files? E.g. what happens if two processes try to create a lock file at the same time?