如何确保我的bash脚本尚未运行? [英] How do I make sure my bash script isn't already running?

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

问题描述

我有一个bash脚本我想从cron每5分钟运行......但有一个机会在脚本的previous运行不这样做没有......在这种情况下,我想新的运行刚刚退出。我不想依靠在/ tmp目录只是一个锁定文件。我要确保确保过程实际上是运行之前,我兑现了锁定文件(或其他)...

下面是我从网上至今被盗......我如何变得聪明起来了一点?或者是有那最好不过了一种完全不同的方式?

 如果[-f / tmp目录/ mylockFile]然后
  回声'脚本仍在运行
其他
  回音1 GT;的/ tmp / mylockFile
  / *做一些东西* /
  RM -f / tmp目录/ mylockFile
科幻


解决方案

 #使用含有正在运行的进程的PID文件锁
#如果脚本崩溃并离开锁文件身边,就会产生不同的PID这样
#不会prevent脚本重新运行。

LF =的/ tmp / pidLockFile
#创建空锁文件,如果不存在
猫的/ dev / null的>> $ LF
阅读lastPID< $ LF
#如果lastPID不为空,并与PID进程存在,退出
[! -z$ lastPID-a -d的/ proc / $ lastPID]放大器;&安培;出口
回声不运行
#拯救我的PID的锁定文件
回声$$> $ LF
#睡眠只是为了使测试更加简单
睡眠5

有此脚本中至少有一个竞争状态。不要使用它的生命支持系统,哈哈。但它应该工作的罚款你的榜样,因为你的环境不同时启动两个脚本。有很多方法可以使用​​更多的原子锁,但他们一般依赖于具有可以安装一个特定的事物,或工作在不同的NFS,等等...

I have a bash script I want to run every 5 minutes from cron... but there's a chance the previous run of the script isn't done yet... in this case, i want the new run to just exit. I don't want to rely on just a lock file in /tmp.. I want to make sure sure the process is actually running before i honor the lock file (or whatever)...

Here is what I have stolen from the internet so far... how do i smarten it up a bit? or is there a completely different way that's better?

if [ -f /tmp/mylockFile ] ; then
  echo 'Script is still running'
else
  echo 1 > /tmp/mylockFile
  /* Do some stuff */
  rm -f /tmp/mylockFile
fi

解决方案

# Use a lockfile containing the pid of the running process
# If script crashes and leaves lockfile around, it will have a different pid so
# will not prevent script running again.
# 
lf=/tmp/pidLockFile
# create empty lock file if none exists
cat /dev/null >> $lf
read lastPID < $lf
# if lastPID is not null and a process with that pid exists , exit
[ ! -z "$lastPID" -a -d /proc/$lastPID ] && exit
echo not running
# save my pid in the lock file
echo $$ > $lf
# sleep just to make testing easier
sleep 5

There is at least one race condition in this script. Don't use it for a life support system, lol. But it should work fine for your example, because your environment doesn't start two scripts simultaneously. There are lots of ways to use more atomic locks, but they generally depend on having a particular thing optionally installed, or work differently on NFS, etc...

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

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