【发布时间】:2023-04-07 00:56:02
【问题描述】:
我正在尝试让多个独立进程使用系统范围的锁来协调它们对文件的写入(请参阅此处:Concurrent file accesses from different scripts python)
锁需要跨越整个系统,因为进程是在不同时间独立产生的。在这里:System-wide mutex in Python on Linux 我读到fcntl.lockf 应该做我想做的事,但我无法让它工作。这是我尝试过的:
1号航站楼
>>> import fcntl
>>> f = open('myfile', 'w')
>>> fcntl.lockf(f, fcntl.LOCK_EX)
[Detach from terminal]
2号航站楼
>>> f = open('myfile', 'w')
>>> f.write('hello')
5
>>> f.close()
[Detach from terminal]
如果我检查文件,它包含“你好”。所以没有锁!我做错了什么?我已经尝试过 ubuntu16.04 和 macOS High sierra,并得到了相同的结果。我正在使用 python 3.6
【问题讨论】:
-
两个进程都必须使用文件锁定才能工作。
-
@cdarke 啊,谢谢!我错过了。如果你回答我会接受它:-)
-
您是否希望在第一个进程结束后保留一个锁? (因为它不会)
-
@cdarke 当然,我知道这一点。不,在进程结束后锁死是完全没问题的 :)
标签: python linux macos file locking