Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import fcntl
- from multiprocessing import Process
- class SingleInstanceError: pass
- class InterProcessLockFcntl:
- type = "fcntl"
- def __init__(self, name=None, raise_on_no_lock=False, Tag=""):
- self.lockf = 0
- self.raise_on_no_lock = raise_on_no_lock
- self.Tag = Tag
- if not name:
- name = sys.argv[0]
- self.name = name # base64.b64encode(name).replace('=','')
- self.fname = os.path.join('/tmp',self.name + '.lock')
- assert(os.path.isdir('/tmp'))
- def acquire(self):
- self.lockf = open(self.fname, 'w')
- try:
- fcntl.flock(self.lockf, fcntl.LOCK_EX | fcntl.LOCK_NB)
- except IOError:
- self.lockf.close()
- self.lockf = 0
- if self.raise_on_no_lock is True:
- raise SingleInstanceError
- else:
- print self.Tag, "NO ACQUIRE"
- return False
- print self.Tag, "ACQUIRE"
- return True
- def release(self):
- try:
- print self.Tag, "RELEASE"
- os.unlink(self.fname)
- self.lockf.close()
- except OSError:
- print self.Tag, "RELEASE - FAIL"
- def f(name, i):
- l = InterProcessLockFcntl( name, Tag=i )
- rc = l.acquire()
- if rc is True:
- l.release()
- for num in range(100):
- Process(target=f, args=("yh_lock_file", num)).start()
- sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement