本文介绍了确保一次只运行一个 shell 脚本实例的快速而肮脏的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确保在给定时间只运行一个 shell 脚本实例的快速而简单的方法是什么?

What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?

推荐答案

这是一个使用 lockfile 并将 PID 回显到其中的实现.如果进程在删除 pidfile 之前被终止,这将起到保护作用:

Here's an implementation that uses a lockfile and echoes a PID into it. This serves as a protection if the process is killed before removing the pidfile:

LOCKFILE=/tmp/lock.txt
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
    echo "already running"
    exit
fi

# make sure the lockfile is removed when we exit and then claim it
trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
echo $$ > ${LOCKFILE}

# do stuff
sleep 1000

rm -f ${LOCKFILE}

这里的技巧是 kill -0 它不传递任何信号,只是检查具有给定 PID 的进程是否存在.此外,对 trap 的调用将确保 lockfile 被删除,即使您的进程被终止(kill -9 除外).

The trick here is the kill -0 which doesn't deliver any signal but just checks if a process with the given PID exists. Also the call to trap will ensure that the lockfile is removed even when your process is killed (except kill -9).

这篇关于确保一次只运行一个 shell 脚本实例的快速而肮脏的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:14