• Uncategorized

About python : flock-disappearing-after-parent-die

Question Detail

I take flock then fork, and expect that “lock” would be unlocked
only when child and parent died.
But after parent process finished,
assert triggered:

test.lck NOT found in lslocks output
Traceback (most recent call last):
  File "daemon_and_flock.py", line 25, in <module>
    assert check_lock(path)
AssertionError

Any idea how to fix this, and force lock to stay alive until all related file descriptors were closed in both child and parent proceces?

import fcntl, sys, os, subprocess, time

def check_lock(path: str) -> bool:
    lines = subprocess.check_output(["lslocks"]).decode('utf-8')
    for line in lines.split('\n'):
        if path in line:
            print(f"{path} found in lslocks output")
            return True
    print(f"{path} NOT found in lslocks output")
    return False
        
path = sys.argv[1]
fh = open(path, "a")
fcntl.flock(fh, fcntl.LOCK_EX)
assert check_lock(path)
print(f"before fork: file handle {fh.fileno()}")

pid = os.fork()
if pid == 0:
    print(f"child: file handle {fh.fileno()}")
    assert check_lock(path)
    time.sleep(1)
    assert check_lock(path)
else:
    print(f"parent: file handle {fh.fileno()}")
    assert check_lock(path)

Question Answer

No answer for now.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.