Вы можете использовать флаги POSIX O_EXCL
и O_CREAT
для 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.