确保一次只运行一个 shell 脚本实例的快速而肮脏的方法

编程入门 行业动态 更新时间:2024-10-08 00:27:18
本文介绍了确保一次只运行一个 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 脚本实例的快速而肮脏的方法

本文发布于:2023-11-24 00:49:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:肮脏   脚本   实例   快速   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!