问题描述
确保给定脚本的仅一个实例正在运行的最简单/最佳方法是什么(假设它是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脚本只有一个实例正在运行的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!