Created
April 27, 2016 20:25
-
-
Save rohityadavcloud/5d9983e7d58311ba8e517eefd931a507 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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