From: karim hamidou Date: Thu, 7 Nov 2013 18:53:30 +0000 (+0100) Subject: basic file lock X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=f534cc3bbc877ac3811644d622eaa9514b70c501;p=kite.git basic file lock --- 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 + + +