检查进程是否正在运行,甚至在cron下

我有一个每分钟运行一次的cron作业,但是如果find数据,可能需要很多分钟才能完成。

我需要告诉脚本的另一个实例是否从另一个实例运行。 为了使事情更有趣,我们使用不同的参数调用相同的脚本。例如:

* * * * * /home/user/script.sh Dir1 > /tmp/logdir1.log * * * * * /home/user/script.sh Dir2 > /tmp/logdir2.log 

我曾经testing过这样的东西:

 FORMAT="`basename $0` $1" OLDPID=`pgrep -f -o "${FORMAT}"` #grab the oldest copy of the PID matching this format echo $OLDPID:$$ If [ "$OLDPID" -eq "$$" ] 

….

在我的testing中,这个效果很好,如果最老的PID与当前的不一样,那么还有另外一个正在运行。 但是,从cron运行时,进程会出现两次,所以最早的PID不是当前的:

 user 1094 0.0 0.0 8720 944 ? Ss 12:38 0:00 \_ /bin/sh -c /home/user/script.sh Dir1 > /tmp/logdir1.log user 1097 0.1 0.0 8856 1236 ? S 12:38 0:00 \_ /bin/bash /home/user/script.sh Dir1 

所以我的脚本每次都会失败,因为它看起来是重复的。 有没有办法告诉pgrep忽略第一个?

过去我们在阅读pidfile时遇到了一些问题,然后看看这个过程是否还在运行。 (其他进程得到相同的PID,不同版本的centos似乎有略微不同的PS参数)

你将如何解决这个问题?

使用重叠作业 – locking中描述的flock。

做这样的事情:

 #!/bin/bash pidfile=/var/run/myscript.pid if [ -f ${pidfile} ]; then # is there already a pid file? oldpid=$(cat ${pidfile}) ps -p ${oldpid} &> /dev/null # is the process still running? if [ $? -ne 0 ]; then rm ${pidfile} # pid file is stale, remove it else echo "Old process still running" exit 1 fi fi echo $$ > ${pidfile} # DO STUFF rm ${pidfile}