13

The "standard" locking snippet I've seen goes something like...

(
    flock -n 200 || exit 1;
    # do stuff
) 200>program.lock

Is it safe (testing seems to say so) to use exec at that point? Will the subprocess retain the lock?

(
    flock -n 200 || exit 1;
    exec /usr/bin/python vendors-notcoolstuff.py
) 200>program.lock

I vaguely remember exec'd processes retain open file descriptors and since flock uses file descriptors it should work. But I cannot find any documentation that makes that definitive and clear.

For the record, this is specific to Linux.

2 Answers 2

6

Yes, it is. Exec just replaces the process image, but it's still the same process so the OS-level locks associated with it remain the same.

It's very easy to verify that it works:

lock

(
    flock -n 200 || exit 1;
    echo "locked"
    exec ./script
) 200>program.lock

script

sleep 100

Try running ./lock twice within then next 100 seconds. You'll only get the lock once, ergo exec does not release the lock.

3

Yes, locks are preserved across exec. Locks are preserved across the underlying system call execve, as long as the file descriptor remains open. File descriptors remain open across execve unless they have been configured to be closed on exec, and file descriptors created by shell redirection are not marked as close-on-exec.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .