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}
#################
# your stuff here
#################
rm -f ${LOCKFILE}
说明:
kill -0不会产生任何信号, 而会检查给定的pid的进程是不是存在
The trick here is the kill -0 which doesn’t deliver any signal but just checks if a process with the given PID exists
trap命令用于指定在接收到信号后将要采取的动作,常见的用途是在脚本程序被中断时完成清理工作。
trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
就是说当收到INT TERM EXIT
, 这几个信号之一时,
执行动作rm -f ${LOCKFILE}
.$$表示当前脚本的进程id
参考: