您好,登录后才能下订单哦!
shell脚本如何防止重复执行,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
代码如下:
#!/bin/bash
#
# file locking using bash.
# ver 0.1.6
#
# author : malundao ( malundao@sina.com )
# date : 2011-08-31
# ref : http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2005-09/0472.html
#
# note:
# shflock_cleanhook() is a user defined function to clean up user-specific sth.
#
# /path/to/lock/. note; directory, not a file.
# should be modified
LOCKPATH="/tmp"
cleanup() {
shflock_cleanhook
cd $LOCKPATH
[ -e lock.pid ] || exit
read pid >/dev/null 2>&1 <lock.pid
if [ -n "$pid" ]; then
if [ "$pid" == "$$" ]; then
rm -f lock.$pid
rm -f lock.pid
exit
fi
fi
exit
}
# trap EXIT ?
trap 'cleanup' HUP INT TERM
getlock() {
oldpath=`pwd`
cd $LOCKPATH
while
echo $$ > lock.$$
[ -e lock.pid ]
do
rm lock.$$
read pid >/dev/null 2>&1 <lock.pid
if [ -n "$pid" ]; then
if [ -e /proc/$pid ]; then
cd $oldpath
return 1 # Lock is taken by others
else
#unsafe: rm -f lock.$pid
echo WARN: please delete stale lock.pid by HAND.
return 2
fi
else
# sleep some seconds,then back to 'while' loop
# 11 is a prime number, $$ as a random.
echo sleep $(( $$ % 11 ))
sleep $(( $$ % 11 ))
fi
done
# 'ln -s' is an atom op.
ln -s lock.$$ lock.pid >/dev/null 2>&1
if [ $? -eq 0 ]; then
cd $oldpath
return 0 # We got the lock
else
[ -e lock.pid ] || echo WARN: please delete hanging lock.pid by HAND.
cd $oldpath
return 3 # Lock is probably taken by others.
fi
}
putlock () {
oldpath=`pwd`
cd $LOCKPATH && rm -f lock.$$ lock.pid
cd $oldpath
}
## test
shflock_cleanhook() {
echo i\'m a hook.
}
while true; do
while ! getlock; do
#echo wait a second...
sleep 1
done
echo \[$$\] `date` ,now hold lock for 3 seconds...
sleep 3
#echo putlock
putlock
sleep 1 # yield
done
防止脚本多次执行(一)
代码如下:
while [ `ps x |grep -v grep|grep filename.sh|wc -l` -gt 0 ];
do
exit
done
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。