]> khamidou — GitHub mirrors - kite.git/commitdiff
basic file lock
authorkarim hamidou <khamidou@gmail.com>
Thu, 7 Nov 2013 18:53:30 +0000 (19:53 +0100)
committerkarim hamidou <khamidou@gmail.com>
Thu, 7 Nov 2013 18:53:30 +0000 (19:53 +0100)
src/back/kite/lockfile.py [new file with mode: 0644]
src/back/tests/test_lockfile.py [new file with mode: 0644]

diff --git a/src/back/kite/lockfile.py b/src/back/kite/lockfile.py
new file mode 100644 (file)
index 0000000..750a2e8
--- /dev/null
@@ -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 (file)
index 0000000..3cb7911
--- /dev/null
@@ -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
+        
+    
+