#!/usr/bin/python3 import fcntl import sys import time def library_function(): # library function opens its own /var/tmp/testing file descriptor # We have no control over what library_function does # We have the lock so we expect this to happen with open('/var/tmp/testing', 'ab') as fd: fd.write(b'some data') # library_function closes its /var/tmp/testing file descriptor # Because we used lockf, we lose the file descriptor unexpectedly here call_library_function = False if len(sys.argv) >= 2: print('calling library function in this run') call_library_function = True with open('/var/tmp/testing', 'ab') as fd: print('long-hold acquired lock') fcntl.lockf(fd, fcntl.LOCK_EX) if call_library_function: library_function() time.sleep(5) print('long-hold exiting, expect to lose the lock when it exits')