Is flock & exec safe in bash?

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
) 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.

Asked By: Danny


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:


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


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.

Answered By: PSkocik

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.

Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.