shell脚本中是否有互斥/信号量机制?
我正在 shell 脚本中寻找互斥/信号量/并发机制。 考虑以下情况: 除非“a”用户不关闭共享文件,否则“b”用户应该无法打开/更新它。 我只是想知道如何在 shell 脚本中实现互斥量、信号量、临界区等。
在 shell 脚本中实现锁定机制[文件级别]的最简单方法是什么?
I'm looking for mutex/semaphore/concurrency mechanism in shell script.
Consider following situation:
Unless "a" user does not close the shared file, "b" user should not able to open/update it.
I'm just wondering how to implement mutex, semaphore, critical sections, etc. in shell scripting.
Which is the easiest way to implement locking mechanism [file level] in shell scripting?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
BashFAQ
shellter 指出有一些很好的例子。我将其移至此处以便页面是独立的,其基本思想是使用同时测试和设置的操作: mkdir
如果目录存在,mkdir 将失败;如果不存在,则 mkdir 将创建。这是一个原子操作,您可以像这样在 shell 脚本中使用它来执行互斥(来自上面的 BashFAQ),
请点击链接以获取有关清理和其他项目的更多详细信息。
The BashFAQ
noted by shellter has some good examples. The basic idea, which I'm moving here so the page is self-contained, is to use an operation that both tests and sets at the same time: mkdir
mkdir will fail if the directory exists and will make it if it does not. It's an atomic operation and you can use it like so to do a mutex in your shell script (from the above BashFAQ)
follow the link for more detail on cleanup and other items.
您可以使用
flock
实用程序来锁定文件/将其用作互斥体。示例:
用法示例:(
回复
massimo 的观点:
如果您不想硬编码文件描述符编号 (如果你没有硬编码 0、1 或 2,那么它应该很少成为问题,但无论如何),然后在 bash 中
(但不是在仅 POSIX shell 中)你可以让系统为你选择一个 fd
:)
You can use the
flock
utility to lock a file / use it as a mutex.Example:
Example usage:
(
In reply to massimo's point:
If you don't want to hardcode a filedecriptor number (it should rarely be a problem if you aren't hardcoding 0, 1, or 2, but anyway), then in bash
(but not in a POSIX only shell) you can have the system pick a fd for you with:
)
请参阅 BashFAQ 和 ProcessManagment 有关 Bash 中文件锁定的讨论。
将您的问题标记为 shell(仅)会限制可以帮助您的人数。您可能想要添加 unix、ksh、bash。
这里已经发布了许多关于这个主题的问题/答案,所以
我希望这会有所帮助。
See BashFAQ and ProcessManagment for discussions on file locking in Bash.
Tagging your question as shell (only) limits the number of people that can help you. You may want to add unix, ksh, bash.
There are numerous questions/answers on this topic posted here already on S.O.
I hope this helps.
您将希望防止持续轮询,并使用类似中断的机制。
为此,请使用内存中的文件(运行目录),并等待它被另一个进程更改:
You will want to prevent constant polling, and use an interruption like mechanism instead.
For that use a file in memory (run directory), and wait it to be changed by another process:
我需要一个 bash 函数的互斥锁,我正在做
在函数的开头,然后在函数的结尾,我正在做
I needed a mutex for a bash function, and I am doing
At the beginning of the function and then at the end of the function, I am doing