以确保只有1 bash脚本的副本最好的办法是在运行? [英] The best way to ensure only 1 copy of bash script is running?
问题描述
什么是确保只有1定的脚本运行的副本最简单/最佳方法 - 假定它是在Linux上的bash
What is the simplest/best way to ensure only 1 copy of given script is running - assuming it's bash on linux?
目前我做的那一刻:
ps -C script.name.sh > /dev/null 2>&1 || ./script.name.sh
但它有几个问题:
but it has several issues:
- 它使检查脚本之外
- 它不会让我跑,从不同的帐户在同一个脚本 - 我有时会想
- -C只检查前14个进程名的字符
当然,我可以写我自己处理了pidfile,但我感到,应该有一些简单的方法来做到这一点。
Of course I can write my own pidfile handling, but I sense that there should be some simple way to do it.
推荐答案
如果脚本在所有用户都是相同的,你可以使用锁文件
办法。如果您获得了锁,否则继续显示消息并退出。
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
这篇关于以确保只有1 bash脚本的副本最好的办法是在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!