确保在给定时间只运行一个 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 脚本实例的快速而肮脏的方法
发布评论