首页 > 代码库 > 高频运行脚本案例 $$

高频运行脚本案例 $$

    在执行定时任务脚本频率比较快,并不知道上一次的脚本是否真正执行完毕,但是业务要求同一个时刻只能有一个同样的脚本运行,此时就可以利用$$获取上次的运行的脚本进程号,当程序重新运行时候,根据所得进程号,清理掉上一次的进程,运行新的脚本命令,脚本如下:

root@ubuntu:/shell# cat cmz.sh
#!/bin/bash
pidpath=/tmp/cmz.pid
if [ -f "$pidpath" ];then
    kill $(cat $pidpath)>/dev/null 2>&1
    rm -rf $pidpath
fi
echo $$>$pidpath  
sleep 100

测试:

#第一次后台运行
root@ubuntu:/shell# sh cmz.sh & 
[5] 5232
root@ubuntu:/shell# cat /tmp/cmz.pid
5232
[4]-  Terminated              sh cmz.sh
root@ubuntu:/shell# ps -ef |grep cmz.sh
root       5232   5063  0 10:56 pts/1    00:00:00 sh cmz.sh
root       5238   5063  0 10:56 pts/1    00:00:00 grep --color=auto cmz.sh

#第二次后台运行
root@ubuntu:/shell# sh cmz.sh &
[6] 5239
root@ubuntu:/shell# cat /tmp/cmz.pid
5239
[5]-  Terminated              sh cmz.sh
root@ubuntu:/shell# ps -ef |grep pid.sh
root       5239   5063  0 10:56 pts/1    00:00:00 sh cmz.sh
root       5245   5063  0 10:56 pts/1    00:00:00 grep --color=auto cmz.sh

从上面来看此时同一时刻只有一个进程在运行,此时在运行第二次时候,发现之前进程没运行结束,此时就kill掉,再次运行,要是必须运行完毕后在紧接着运行,代码需要稍微修改即可。

高频运行脚本案例 $$