Skip to content

Instantly share code, notes, and snippets.

@mnencia
Created December 7, 2016 10:36
Show Gist options
  • Select an option

  • Save mnencia/c357fc121d15aca20eccf61fe44ed88f to your computer and use it in GitHub Desktop.

Select an option

Save mnencia/c357fc121d15aca20eccf61fe44ed88f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import time
from barman.lockfile import LockFile, LockFileBusy
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: %s file_to_lock' % sys.argv[0], file=sys.stderr)
sys.exit(2)
try:
lock = LockFile(sys.argv[1])
lock.acquire(raise_if_fail=True, wait=False)
pid = os.fork()
if pid == 0:
# Child process: loop endlessly
# detach from parent session
os.setsid()
# close every descriptor different from the locked file
for fd in range(0, 1024):
try:
if fd != lock.fd:
os.close(fd)
except OSError: # ERROR, fd wasn't open to begin with (ignored)
pass
# loop forever
while True:
time.sleep(1)
# Parent process: print the pid and exit
print('%d' % pid)
sys.stdout.flush()
# To keep the acquired lock, we don't want any process cleanup
# for the father process. Exit immediately.
# noinspection PyProtectedMember
os._exit(0)
except LockFileBusy:
print('Lock acquisition failed on file "%s"' % sys.argv[1])
sys.stdout.flush()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment