harlowja / fasteners

A python package that provides useful locks.
Apache License 2.0
246 stars 45 forks source link

Consider proving a flock based lock #53

Open psarka opened 3 years ago

psarka commented 3 years ago

@redramen writes:

I tried using the default fcntl lock with a daemon process (one generated by python-daemon package) but was running into a few issues. Notably I could not write my PID to a file, nor could I read it back with that style of locking. I can do those with the BSD style flock.

And provides the following snippet:

class _FlockLock(_InterProcessLock):
    """Interprocess lock implementation that works on posix systems based
    on https://www.man7.org/linux/man-pages/man2/flock.2.html."""

    @staticmethod
    def _trylock(lockfile):
        fileno = lockfile.fileno()
        fcntl.flock(fileno, fcntl.LOCK_EX | fcntl.LOCK_NB)

    @staticmethod
    def _unlock(lockfile):
        fileno = lockfile.fileno()
        fcntl.flock(fileno, fcntl.LOCK_UN)