Skip to content

Instantly share code, notes, and snippets.

@rohityadavcloud
Created April 27, 2016 20:25
Show Gist options
  • Save rohityadavcloud/5d9983e7d58311ba8e517eefd931a507 to your computer and use it in GitHub Desktop.
Save rohityadavcloud/5d9983e7d58311ba8e517eefd931a507 to your computer and use it in GitHub Desktop.
import fcntl
# Expected output:
# lock acquired
# failed to lock
# lock acquired
lf = '/tmp/some.lock'
h = None
def lock(path):
global h
try:
# w is used so we don't re-use the same FD, this simulates as if separate programs are running this code
w = None
if not h:
h = open(lf, 'w')
w = h
else:
w = open(lf, 'w')
fcntl.flock(w, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
return False
print 'lock acquired'
return True
if not lock(lf):
print 'failed to lock'
if not lock(lf):
print 'failed to lock'
h.close()
if not lock(lf):
print 'failed to lock'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment