Advertisement
Guest User

code that shows bug in python file locking code

a guest
Jan 28th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. import os
  2. import fcntl
  3. from multiprocessing import Process
  4.  
  5. class SingleInstanceError: pass
  6. class InterProcessLockFcntl:
  7. type = "fcntl"
  8. def __init__(self, name=None, raise_on_no_lock=False, Tag=""):
  9. self.lockf = 0
  10. self.raise_on_no_lock = raise_on_no_lock
  11. self.Tag = Tag
  12. if not name:
  13. name = sys.argv[0]
  14. self.name = name # base64.b64encode(name).replace('=','')
  15. self.fname = os.path.join('/tmp',self.name + '.lock')
  16. assert(os.path.isdir('/tmp'))
  17.  
  18. def acquire(self):
  19. self.lockf = open(self.fname, 'w')
  20. try:
  21. fcntl.flock(self.lockf, fcntl.LOCK_EX | fcntl.LOCK_NB)
  22. except IOError:
  23. self.lockf.close()
  24. self.lockf = 0
  25. if self.raise_on_no_lock is True:
  26. raise SingleInstanceError
  27. else:
  28. print self.Tag, "NO ACQUIRE"
  29. return False
  30. print self.Tag, "ACQUIRE"
  31. return True
  32.  
  33. def release(self):
  34. try:
  35. print self.Tag, "RELEASE"
  36. os.unlink(self.fname)
  37. self.lockf.close()
  38. except OSError:
  39. print self.Tag, "RELEASE - FAIL"
  40.  
  41. def f(name, i):
  42. l = InterProcessLockFcntl( name, Tag=i )
  43. rc = l.acquire()
  44. if rc is True:
  45. l.release()
  46.  
  47. for num in range(100):
  48. Process(target=f, args=("yh_lock_file", num)).start()
  49.  
  50. sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement