快速和肮脏的方式,以确保shell脚本只有一个实例同时运行 [英] Quick-and-dirty way to ensure only one instance of a shell script is running at a time

查看:131
本文介绍了快速和肮脏的方式,以确保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?

推荐答案

下面是一个使用的锁文件的呼应和一个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}

这里的窍门是杀-0 不提供任何信号,只是检查,如果给定PID的过程中存在。还调用陷阱将确保的锁文件的当你的进程被终止(除甚至删除杀死-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脚本只有一个实例同时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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