`exec 200>lockfile` 有什么作用?
What does `exec 200>lockfile` do?
我不熟悉 exec
命令。关于如何锁定文件的 bash 教程抛出了这个:
exec 200>lockfile
flock 200
...
flock -u 200
我知道它正在创建一个名为 lockfile
的文件并为其分配 200 的 FD。然后第二个命令锁定该文件。处理完文件后,最后一个命令将其解锁。
这样做,同一脚本的任何其他并发实例将停留在第二行,直到第一个实例解锁文件。酷
现在,我不明白的是exec
在做什么。
直接从 bash 命令行,两个选项似乎都有效:
exec 200>lockfile
200>lockfile
但是当在脚本中使用第二个选项时,会引发“错误的文件描述符错误”。
为什么需要 exec
来避免错误?
--- 编辑 ---
经过更“认真的研究”,我找到了答案 here。 exec
命令使 FD 停留在整个脚本或当前 shell.
这样做:
200>lockfile flock 200
会起作用的。但稍后 flock -u 200
会引发“错误的 FD 错误”。
The manual seems to mention shell replacement with given command. What does that has to do with file descriptors?
这个在第二句有解释:
exec: exec [-cl] [-a name] file [redirection ...]
Exec FILE, replacing this shell with the specified program.
If FILE is not specified, the redirections take effect in this
shell. [...]
本质上,从 myscript.sh
内部执行 exec 42> foo.txt
打开 foo.txt
以便在当前进程中写入 FD 42。
这类似于首先来自 shell 的 运行 ./myscript.sh 42> foo.txt
,或者在 C 程序中使用 open
和 dup2
。
我不熟悉 exec
命令。关于如何锁定文件的 bash 教程抛出了这个:
exec 200>lockfile
flock 200
...
flock -u 200
我知道它正在创建一个名为 lockfile
的文件并为其分配 200 的 FD。然后第二个命令锁定该文件。处理完文件后,最后一个命令将其解锁。
这样做,同一脚本的任何其他并发实例将停留在第二行,直到第一个实例解锁文件。酷
现在,我不明白的是exec
在做什么。
直接从 bash 命令行,两个选项似乎都有效:
exec 200>lockfile
200>lockfile
但是当在脚本中使用第二个选项时,会引发“错误的文件描述符错误”。
为什么需要 exec
来避免错误?
--- 编辑 ---
经过更“认真的研究”,我找到了答案 here。 exec
命令使 FD 停留在整个脚本或当前 shell.
这样做:
200>lockfile flock 200
会起作用的。但稍后 flock -u 200
会引发“错误的 FD 错误”。
The manual seems to mention shell replacement with given command. What does that has to do with file descriptors?
这个在第二句有解释:
exec: exec [-cl] [-a name] file [redirection ...]
Exec FILE, replacing this shell with the specified program.
If FILE is not specified, the redirections take effect in this
shell. [...]
本质上,从 myscript.sh
内部执行 exec 42> foo.txt
打开 foo.txt
以便在当前进程中写入 FD 42。
这类似于首先来自 shell 的 运行 ./myscript.sh 42> foo.txt
,或者在 C 程序中使用 open
和 dup2
。