Linux:如何防止同一个shell脚本同时执行?

4 篇文章 1 订阅

对于如何防止同一个shell脚本同时执行,一般有2种比较简单的方式:

  • trap Exit
  • flock

一、trap Exit

原理说明:

在shell脚本中,trap Exit会为Exit信号配置一个信号处理器,当执行的脚本因正常执行完成或执行出错而要退出时,会执行指定的命令或函数。

脚本防止同时执行实现流程:

1、使用一个文件充当锁。

2、当脚本执行时,先判断锁文件是否存在,若锁文件不存在,则创建这个锁文件,然后继续执行脚本;若锁文件存在,说明已经有一个脚本正在执行,直接终止当前脚本的执行。
3、当脚本正常执行完成时,删除这个锁文件。为了防止脚本异常退出而无法删除锁文件,因而采用trap Exit机制删除锁文件。

 形式1:

trap 'commands_to_execute_before_exit' EXIT

形式2:

function some_function(){
  #some commands
}
trap some_function EXIT

二、flock

形式:

flock /path/to/file --command "the_actual_command"

参数说明:

不带参数 排它锁
-s       共享锁
-u       解锁
-n       若未获取到锁,不等待,也不执行命令

三、举例

 比如有一个脚本somework.sh

如果是采用trap Exit的方式,可以在somework.sh脚本的开头添加如下函数查重

checkRepeat() {
	lockFile="task.lock"
	
	if [ -f "${lockFile}" ]
	then
		# 读取lock文件中记录的pid
		anotherPid=$(cat ${lockFile})
		# 获取正在执行的脚本的信息
		procInfo=$(ps -ef | grep "${anotherPid}" | grep -v grep)
		
		echo "another script is running. current pid: $$. another pid: ${anotherPid}. another script info:"
		echo "${procInfo}"
	else
		# 创建lock文件
		touch ${lockFile}
		# 将当前进程编号写入lock文件
		echo $$ > ${lockFile}
		
		# 脚本退出前删除lock文件
		trap "printLog \"remove ${lockFile}\"; rm ${lockFile}" EXIT
	fi
}

checkRepeat

# do something

如果是采用flock的方式,只需要通过如下方式调用somework.sh脚本

flock task.lock ./somework.sh

参考文档

https://linuxsimply.com/bash-scripting-tutorial/process-and-signal-handling/signals-handling/bash-trap/
https://linuxsimply.com/bash-scripting-tutorial/process-and-signal-handling/signals-handling/trap-exit/
https://www.man7.org/linux/man-pages/man1/trap.1p.html
https://www.baeldung.com/linux/file-locking
https://linuxhandbook.com/flock-command/
https://linuxhandbook.com/file-locking/

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值