问题描述
确保只运行给定脚本的一个实例的最简单/最好的方法是什么 - 假设它是 Linux 上的 Bash?
What is the simplest/best way to ensure only one instance of a given script is running - assuming it's Bash on Linux?
目前我正在做:
ps -C script.name.sh > /dev/null 2>&1 || ./script.name.sh
但它有几个问题:
- 它将检查放在脚本之外
- 它不允许我从不同的帐户运行相同的脚本 - 我有时希望这样做.
-C
只检查进程名称的前 14 个字符
- it puts the check outside of script
- it doesn't let me run the same script from separate accounts - which I would like sometimes.
-C
checks only first 14 characters of process name
当然,我可以编写自己的 pidfile 处理,但我觉得应该有一个简单的方法来做到这一点.
Of course, I can write my own pidfile handling, but I sense that there should be a simple way to do it.
推荐答案
如果所有用户的脚本都相同,您可以使用 lockfile
方法.如果您获得了锁,请继续,否则会显示一条消息并退出.
If the script is the same across all users, you can use a lockfile
approach. If you acquire the lock, proceed else show a message and exit.
举个例子:
[Terminal #1] $ lockfile -r 0 /tmp/the.lock
[Terminal #1] $
[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] lockfile: Sorry, giving up on "/tmp/the.lock"
[Terminal #1] $ rm -f /tmp/the.lock
[Terminal #1] $
[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] $
获得/tmp/the.lock
后,您的脚本将是唯一可以执行的脚本.完成后,只需取下锁即可.在脚本形式中,这可能如下所示:
After /tmp/the.lock
has been acquired your script will be the only one with access to execution. When you are done, just remove the lock. In script form this might look like:
#!/bin/bash
lockfile -r 0 /tmp/the.lock || exit 1
# Do stuff here
rm -f /tmp/the.lock
这篇关于确保只有一个 Bash 脚本实例正在运行的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!