flock

flock: when to use the -o (--close) option?


According to the flock manual, the -o or --close option is described like this:

Close the file descriptor on which the lock is held before executing command. This is useful if command spawns a child process which should not be holding the lock.

I don't understand what this means in practice. Can you provide some example commands/scenarios where this option would be helpful?


Solution

  • I was just trying to determine this myself! The man page does not provide a clear description:

       -o, --close
             Close the file descriptor on which the lock is held before executing command.  This is useful if command spawns a child process which should not be holding the lock.
    

    My question was... what is the point of having a lock if you're releasing it before the command executes? I found an answer here: https://utcc.utoronto.ca/~cks/space/blog/linux/FlockUsageNotes

    It states:

    flock -n -o LOCKFILE SHELL-SCRIPT [ARGS ...]

    Run this way, the only thing holding the lock is flock itself. When flock exits (for whatever reason), the file descriptor will be closed and the lock released, even if SHELL-SCRIPT is still running.