Search code examples
shellfilehttp-redirectdescriptor

What is the "200" in this shell redirection command? File descriptor?


What is the "200" in this command? I assume it's a file descriptor but why 200? Is that a safe choice in all cases?

(
flock -s 200

# ... commands executed under lock ...

) 200>/var/lock/mylockfile

I copied this from the flock man page.

Here's how I would have coded it. Here I'm only locking access to one command, sleep 1. I like the above version because it supports locking a batch of commands. But I want to understand it before I use it.

flock -x /var/lock/mylockfile sleep 1

Solution

  • Yes, 200 is a file descriptor in the above syntax. When the user picks a FD to redirect, the shell "routes around" that choice: If 200 were previously put to shell-internal use, the shell then copies it to a different number and respects the user's choice. Thus, the only conflicts you need to worry about are those with other user-provided code and tools (and of course standard FDs -- 0/1/2).

    It's not guaranteed by the POSIX spec that 200 will be a legal number -- the mandated number of addressable FDs in POSIX-y shells is much, much lower -- but on a modern system it won't be a problem.

    With bash 4.1 and later, you can have the shell itself pick an available FD.

    (
       exec {lock_fd}>/var/lock/mylockfile || exit
       flock -x "$lock_fd" || exit
       # commands to do with the lock held
    )