From f534cc3bbc877ac3811644d622eaa9514b70c501 Mon Sep 17 00:00:00 2001 From: karim hamidou Date: Thu, 7 Nov 2013 19:53:30 +0100 Subject: [PATCH] basic file lock --- src/back/kite/lockfile.py | 24 ++++++++++++++++++++++++ src/back/tests/test_lockfile.py | 19 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/back/kite/lockfile.py create mode 100644 src/back/tests/test_lockfile.py diff --git a/src/back/kite/lockfile.py b/src/back/kite/lockfile.py new file mode 100644 index 0000000..750a2e8 --- /dev/null +++ b/src/back/kite/lockfile.py @@ -0,0 +1,24 @@ +from fcntl import flock, LOCK_EX, LOCK_UN + +class LockingException(Exception): + pass + +class FileLock(object): + def __init__(self, name, mode): + self.name = name + self.fd = open(name, mode) + + def acquire(self): + flock(self.fd.fileno(), LOCK_EX) + + def release(self): + flock(self.fd.fileno(), LOCK_UN) + self.fd.close() + self.fd = None + + def __enter__(self): + self.acquire() # flock is blocking, so there's no need to handle a timeout + return self + + def __exit__(self, type, value, traceback): + self.release() diff --git a/src/back/tests/test_lockfile.py b/src/back/tests/test_lockfile.py new file mode 100644 index 0000000..3cb7911 --- /dev/null +++ b/src/back/tests/test_lockfile.py @@ -0,0 +1,19 @@ +import kite.lockfile +from kite.lockfile import FileLock +import unittest +import tempfile +import fcntl + +class TestLockfile(unittest.TestCase): + def test_lock(self): + fd, path = tempfile.mkstemp() + print "PATH ", path + with FileLock(path, "r+w"): + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + assert False, "Flock should have failed" + except IOError: + pass + + + -- 2.43.0