Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Created January 27, 2015 03:10
Show Gist options
  • Save Ivlyth/6194320555a65ba5879f to your computer and use it in GitHub Desktop.
Save Ivlyth/6194320555a65ba5879f to your computer and use it in GitHub Desktop.
acquire an exclusive lock on an given fd with non-blocking
import errno
import fcntl
'''
just run this script twice to see different output
'''
'''
`doc string in fcntl.lockf`
When operation is LOCK_SH or LOCK_EX, it can also be bitwise ORed with
LOCK_NB to avoid blocking on lock acquisition.
'''
f = open('test.lock','w')
try:
fcntl.lockf(f,fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as e:
if e.errno in(errno.EACCES, errno.EAGAIN):
print 'locked by other user'
except Exception as e2:
print 'get lock failed'
else:
print 'get lock success'
raw_input()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment