Python lockf and herd behavior

I have read enough stackoverflow posts regarding the b / w flock/lockf/fcntl difference, but I cannot answer the following observation:

 >>> import fcntl >>> a = open('/tmp/locktest', 'w') >>> b = open('/tmp/locktest', 'w') >>> fcntl.lockf(a, fcntl.LOCK_EX | fcntl.LOCK_NB) >>> fcntl.lockf(a, fcntl.LOCK_EX | fcntl.LOCK_NB) >>> fcntl.lockf(b, fcntl.LOCK_EX | fcntl.LOCK_NB) >>> >>> a.close() >>> b.close() >>> a = open('/tmp/locktest', 'w') >>> b = open('/tmp/locktest', 'w') >>> fcntl.flock(a, fcntl.LOCK_EX | fcntl.LOCK_NB) >>> fcntl.flock(a, fcntl.LOCK_EX | fcntl.LOCK_NB) >>> fcntl.flock(b, fcntl.LOCK_EX | fcntl.LOCK_NB) Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 35] Resource temporarily unavailable 

Why is the behavior different in two cases? I know the obvious answer that these are two different locking mechanisms. I'm looking for:

  • What does lockf () or flock () actually do for a file (inode / fd)?
  • According to the demo, do we allow to use the same lock recursively?

I understand the basics of fds and stuff, so I'd rather get a technical answer with more details about the details of the operating system level.

OSX 10.9.3, Python: 2.7.5

+6
source share
1 answer

Good article on this: About file lock breaking

In short:

 - POSIX locks: > lockf() most of the time implemented as just an interface of fcntl() > fcntl() locks are bound to processes, not file descriptors. **If a process has multiple open file descriptors for a particular file, any one of these file descriptors used for acquiring locking will *RESET* the lock.** - BSD lock: > flock() locks are bound to file descriptors, not processes. 

Moreover

Good analysis with tests: Confidential file locking - I accept POSIX and BSD locks

Excerpt from the summary:

 - fcntl and flock style locks are completely orthogonal to each other. Any system providing both(Linux does) will be treating locks obtained through each one of them independently. - Both POSIX and BSD locks are automatically released when the process exits or is aborted. - Both POSIX and BSD locks are preserved across execve calls except when the process has set FD_CLOEXEC flag forcing the file descriptor to be closed, and not inherited by the new process. 
+3
source

Source: https://habr.com/ru/post/982360/


All Articles