bash flock: Why 200? bash flock: Why 200? bash bash

bash flock: Why 200?


Theres nothing special about the number 200. It just happens to be the example used in the man page of the flock command; and it happens to be a large number, so it's unlikely to conflict with the the file descriptor of any other file you open during your script.

In your comment, you ask about:

(   flock -e 200  echo "In critical section"  sleep 5 ) 200>/tmp/blah.lockfile echo "After critical section"

The parentheses () create a subshell; a new process, separate from the parent process. The 200>/tmp/blah.lockfile causes that process to open up /tmp/blah.lockfile for writing, on file descriptor 200. The commands inside the parentheses are executed within that shell.

flock -e 200 obtains an exclusive lock on the file pointed to by file descriptor 200. An exclusive lock means that anyone else who tries to obtain a lock on that file, either exclusive or shared, will block (wait) until this lock has been relinquished, or fail if they hit a timeout or asked not to block. So during the remainder of the body of the subshell (the echo and sleep commands), the lock will be held by that subshell, and no one else can obtain that lock. Once the subshell finishes, the file will be closed and lock relinquished.