如何确保一次仅运行一个Bash脚本实例? [英] How to make sure only one instance of a Bash script is running at a time?

查看:116
本文介绍了如何确保一次仅运行一个Bash脚本实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个sh脚本,该脚本在任何时候最多只能运行一次.

I want to make a sh script that will only run at most once at any point.

说,如果我执行该脚本,然后再次执行该脚本,那么我该如何做,以便如果脚本的第一个exec仍在工作,则第二个脚本将因错误而失败. IE.在执行任何操作之前,我需要检查脚本是否在其他地方运行.我将如何去做?

Say, if I exec the script then I go to exec the script again, how do I make it so that if the first exec of the script is still working the second one will fail with an error. I.e. I need to check if the script is running elsewhere before doing anything. How would I go about doing this??

我运行的脚本运行了很长时间(即永远运行).我想使用cron之类的方法每隔15分钟调用一次脚本,以便万一该过程失败,它将在下一个cron运行脚本中重新启动.

The script I have runs a long running process (i.e. runs forever). I wanted to use something like cron to call the script every 15mins so in case the process fails, it will be restarted by the next cron run script.

推荐答案

您想要一个pid文件,也许像这样:

You want a pid file, maybe something like this:

pidfile=/path/to/pidfile
if [ -f "$pidfile" ] && kill -0 `cat $pidfile` 2>/dev/null; then
    echo still running
    exit 1
fi  
echo $$ > $pidfile

这篇关于如何确保一次仅运行一个Bash脚本实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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