监测同名进程,防止重复调用

来源:互联网 发布:微机室网络还原软件 编辑:程序博客网 时间:2024/04/30 03:49

对于crontab  * * * * *,十分有必要。防止重复调用。

 

这里的进程名是指脚本的完整路径,需能ps到。

 

加在每个程序的开头。

 

方法一:不影响原先的程序,本次退出执行。

 

importsys,commands

if int(commands.getoutput("ps -ef |grep '"+sys.argv[0]+"' |grep -vgrep |wc -l"))>1:

    print "PASS"

   sys.exit(0)

else:

    print "OK"

 

 

 

或者:

方法二:杀掉所有的同名进程,包括本次。

 

##===========================================================================

importos,commands,sys

scriptname=os.path.abspath(sys.argv[0])

RUNNINGSCRIPTCOUNT =commands.getoutput("ps -ef|grep -v grep |grep %s |wc -l "%scriptname)

if int(RUNNINGSCRIPTCOUNT)>1:

    print "已有同名进程运行,杀死所有同名进程。"

    ### linux    awk '{print $2}'

    commands.getoutput("ps -ef|grep -v grep |grep %s |awk '{print $2}' |xargs kill -9 "%scriptname)

    print "exit 0"

   sys.exit(0)

##=============================================================================



方法三: 只杀掉原有进程,保证本次的运行。

先拿到本次进程号,再杀掉其他同名进程号。

0 0
原创粉丝点击