Skip to content

Instantly share code, notes, and snippets.

@wido
Created April 28, 2016 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wido/a236e9f065cef85b0497990e3d4798e6 to your computer and use it in GitHub Desktop.
Save wido/a236e9f065cef85b0497990e3d4798e6 to your computer and use it in GitHub Desktop.
Python file lock test
#!/usr/bin/env python
import time
import fcntl
lock_file = "/var/lock/cloudstack_security_group.lock"
lock_handle = None
def obtain_file_lock(path):
global lock_handle
try:
lock_handle = open(path, 'w')
fcntl.flock(lock_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
return True
except IOError:
pass
return False
if obtain_file_lock(lock_file) is False:
print('Failed to obtain lock!')
else:
print('Obtained lock')
time.sleep(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment