How does this canonical herd example work?

When I need to synchronize programs (shell scripts) through the file system, I found the flock solution to be recommended (should also work in NFS ). Canonical usage example from script (from http://linux.die.net/man/1/flock ):

 ( flock -s 200 # ... commands executed under lock ... ) 200>/var/lock/mylockfile 

I don’t quite understand why this whole construction provides atomicity. In particular, I am wondering in which order flock -s 200 and 200>/var/lock/mylockfile are executed when, for example, bash executes these lines of code. Is this order guaranteed / deterministic? How I understand this should be determinate if this idiom should work. But since an auxiliary shell is generated in the child process, I don’t understand how these two processes are synchronized. I see only the state of the race between the two teams.

I would appreciate it if someone could stop this from disappearing and explain why this design can be used to securely synchronize processes.

At the same time, if someone knows, I would be interested in how safe it is to select only some arbitrary file descriptor (for example, 200 in the example), especially in the context of a large NFS file system with many clients.

+4
source share
1 answer

The whole sub-shell I / O context (...) 200>/var/lock/mylockfile needs to be evaluated - and the I / O redirection is done before any commands can be executed in the sub-shell, so the redirection is always preceded by flock -s 200 . Think about whether the sub-shell has a standard output connected to another command; this pipe must be created before the sub-shell is created. The same applies to file descriptor 200 redirection.

The choice of the file descriptor number does not really matter in the least - in addition, it is not recommended to use file descriptors 0-2 (standard input, output, error). The file name matters; different processes may use different file descriptors; as soon as the name is agreed, it should be fine.

+5
source

Source: https://habr.com/ru/post/1494756/


All Articles