python lockf和flock behaviou

2024-05-20 10:09:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在stackoverflow上阅读了足够多关于差异b/wflock/lockf/fcntl的文章,但我无法回答以下观察结果:

>>> 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

为什么这两种情况下的行为不同?我知道明显的答案,这是两种不同的锁定机制。我在找:

  1. lockf()或flock()实际上对文件(inode/fd)做了什么?
  2. 根据演示,我们是否允许递归地获取相同的锁?

我了解fds和其他东西的基本知识,所以我希望有一个技术性的答案,对操作系统级别的细节有更多的见解。

OSX 10.9.3,Python:2.7.5


Tags: 答案lockclose文章差异openstackoverflowtmp
1条回答
网友
1楼 · 发布于 2024-05-20 10:09:55

一篇关于这个的好文章: On the Brokenness of File Locking

简而言之:

  • POSIX锁:

    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锁:

    flock() locks are bound to file descriptors, not processes.

此外

良好的测试分析: Advisory File Locking – My take on POSIX and BSD locks

摘要摘录:

  • 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.

相关问题 更多 >