避免相同的程序重复运行

Posted by 4Aiur on 04/06/2010 in Shell |

避免相同的程序重复运行的小函数

逻辑如下:

  1. 检查pid文件是否存在,不存在则直接运行程序
  2. 如果pid文件存在,则检查进程中是否存在这个pid
    1. 进程存在此pid则退出
    2. 进程中不存在这一pid,则删除pid文件,程序继续运行

缺点:没有对进程名称进行对比

# Initialize variables
app_path="$(dirname $0)"
pid="${app_path}/run.pid"
# Function
TestPID () {
  if [ -f ${pid} ] ; then
     if ps -p cat ${pid} >/dev/null ; then
        echo "basename $0 is running!  main process id = $(cat ${pid})"
        ps -p cat ${pid} -o cmd=
        exit 1
     else
        rm -f $pid
        echo $$ > ${pid}
     fi
  else
     echo $$ > ${pid}
  fi
}

Tags:

Copyright © 2010-2024 4Aiur All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.