What does 200>“$somefile” accomplish? [duplicate]

风流意气都作罢 提交于 2019-12-12 19:39:49

问题


I've found boilerplate flock(1) code which looks promising. Now I want to understand the components before blindly using it.

Seems like these functions are using the third form of flock

flock [-sxun] [-w timeout] fd

The third form is convenient inside shell scripts, and is usually used the following manner:

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

The piece I'm lost on (from the sample wrapper functions) is this notation

eval "exec $LOCKFD>\"$LOCKFILE\""

or in shorthand from the flock manpage

200>/var/lock/mylockfile

What does that accomplish?

I notice subsequent commands to flock passed a value other than the one in the initial redirect cause flock to complain

flock: 50: Bad file descriptor

It seems like flock is using the file descriptors as a map to know which file to operate on. In order for that to work though, those descriptors would have to still be around and associated with the file, right?

After the redirect is finished, and the lock file is created, isn't the file closed, and file descriptors associated with the open file vaporized? I thought file descriptors were only associated with open files.

What's going on here?


回答1:


200>/var/lock/mylockfile

This creates a file /var/lock/mylockfile which can be written to via file descriptor 200 inside the sub-shell. The number 200 is an arbitrary one. Picking a high number reduces the chance of any of the commands inside the sub-shell "noticing" the extra file descriptor.

(Typically, file descriptors 0, 1, and 2 are used by stdin, stdout, and stderr, respectively. This number could have been as low as 3.)

flock -s 200

Then flock is used to lock the file via the previously created file descriptor. It needs write access to the file, which the > in 200> provided. Note that this happens after the redirection above.



来源:https://stackoverflow.com/questions/21689891/what-does-200somefile-accomplish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!