这个典型的羊群示例是如何工作的? [英] How does this canonical flock example work?

查看:19
本文介绍了这个典型的羊群示例是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当必须通过文件系统同步程序(shell 脚本)时,我发现基于 flock 的解决方案是 推荐(也应该在NFS上工作).在脚本中使用的规范示例(来自 http://linux.die.net/man/1/flock) 是:

When one must synchronize programs (shell scripts) via file system, I have found an flock-based solution to be recommended (should also work on NFS). The canonical example for usage from within a script (from http://linux.die.net/man/1/flock) is:

(
flock -s 200

# ... commands executed under lock ...

) 200>/var/lock/mylockfile 

我不太明白为什么整个结构可以确保原子性.特别是,我想知道 flock -s 200200>/var/lock/mylockfile 的执行顺序是什么,例如bash 执行这些代码行.此订单是否有保证/确定性?按照我的理解,如果这个习语应该起作用,它必须是确定性的.但是由于子shell是在子进程中产生的,我不明白这两个进程是如何同步自己的.我只看到了这两个命令之间的竞争条件.

I don't quite get why this whole construct ensures atomicity. In particular, I am wondering in which order flock -s 200 and 200>/var/lock/mylockfile are executed when e.g. bash executes these lines of code. Is this order guaranteed/deterministic? The way I understand it, it must be deterministic if this idiom should work. But since a sub shell is spawned in a child process, I do not understand how these two processes synchronize themselves. I only see a race condition between these two commands already.

如果有人能消除我对此的困惑并解释为什么可以使用此构造来安全地同步进程,我将不胜感激.

I would appreciate if someone could make my confusion about this disappear and explain why this construct can be used to safely synchronize processes.

同时,如果有人知道,我会对选择任意文件描述符(例如示例中的 200)的安全性感兴趣,尤其是在具有许多客户端的大型 NFS 文件系统.

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

推荐答案

子shell的整个I/O上下文(...) 200>/var/lock/mylockfile必须在子 shell 中执行任何命令之前进行评估 - 并完成 I/O 重定向,因此重定向总是在 flock -s 200 之前.考虑一下子shell是否将其标准输出通过管道传输到另一个命令;必须在创建子外壳之前创建该管道.这同样适用于文件描述符 200 重定向.

The whole I/O context of the sub-shell (...) 200>/var/lock/mylockfile has to be evaluated — and the I/O redirection done — before any commands can be executed in the sub-shell, so the redirection always precedes the flock -s 200. Think about if the sub-shell had its standard output piped to another command; that pipe has to be created before the sub-shell is created. The same applies to the file descriptor 200 redirection.

文件描述符编号的选择实际上并不重要——除此之外,建议不要使用文件描述符 0-2(标准输入、输出、错误).文件名很重要;不同的进程可以使用不同的文件描述符;只要名称一致,应该没问题.

The choice of file descriptor number really doesn't matter in the slightest — beyond it is advisable not to use file descriptors 0-2 (standard input, output, error). The file name matters; different processes could use different file descriptors; as long the name is agreed upon, it should be fine.

这篇关于这个典型的羊群示例是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆