您可以使用POSIX O_EXCL
and O_CREAT
flags to open(2)
以保證只有一個單一的過程中獲取文件,因此數據庫; O_EXCL
將無法通過NFSv2或更早的版本,並且將其用於其他網絡文件系統依然不穩定。
liblockfile
庫實現了open(2)
聯機幫助頁中描述的網絡文件系統安全鎖定機制,這很方便;但我只看到預先製作的Ruby和Perl綁定。根據您的需要,也許提供Python綁定將是有用的,或者可能只是重新實現算法:
O_EXCL Ensure that this call creates the file: if this flag is
specified in conjunction with O_CREAT, and pathname
already exists, then open() will fail. The behavior of
O_EXCL is undefined if O_CREAT is not specified.
When these two flags are specified, symbolic links are not
followed: if pathname is a symbolic link, then open()
fails regardless of where the symbolic link points to.
O_EXCL is only supported on NFS when using NFSv3 or later
on kernel 2.6 or later. In environments where NFS O_EXCL
support is not provided, programs that rely on it for
performing locking tasks will contain a race condition.
Portable programs that want to perform atomic file locking
using a lockfile, and need to avoid reliance on NFS
support for O_EXCL, can create a unique file on the same
file system (e.g., incorporating hostname and PID), and
use link(2) to make a link to the lockfile. If link(2)
returns 0, the lock is successful. Otherwise, use stat(2)
on the unique file to check if its link count has
increased to 2, in which case the lock is also successful.
也許我誤解了,但不能只是重命名每個數據庫的文件位置? – dfb 2011-04-05 23:16:33