Skip to content

Instantly share code, notes, and snippets.

@chris-allan
Last active December 11, 2015 22:48
Show Gist options
  • Save chris-allan/4671879 to your computer and use it in GitHub Desktop.
Save chris-allan/4671879 to your computer and use it in GitHub Desktop.
Attempts to perform an exclusive, non-blocking lock on an open file handle to each file in a directory.
#!/usr/bin/env python
import traceback
import fcntl
import sys
import os
try:
d, = sys.argv[1:]
except ValueError:
print 'Usage: %s <directory>' % sys.argv[0]
sys.exit(1)
for name in os.listdir(d):
path = os.path.join(d, name)
print 'Locking %s:' % path,
f = open(path, 'a+')
try:
fcntl.flock(f, fcntl.LOCK_NB|fcntl.LOCK_EX)
fcntl.flock(f, fcntl.LOCK_UN)
print 'SUCCESS'
except:
#traceback.print_exc()
print 'FAILED'
finally:
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment