简体   繁体   中英

How to kill python script and its children if another instance of it is already running

I need to write a piece of code that will check if another instance of a python script with the same name is running, kill it and all its children and do the job of the script. On my way to solution I have this code:

import os, sys
import time
import subprocess
from subprocess import PIPE,Popen
import os
import signal


if sys.argv[1] == 'boss':
    print 'I am boss', \
        "pid:", os.getpid(), \
        "pgid:", os.getgid()


    # kill previous process with same name
    my_pid=os.getpid()
    pgrep = Popen(['pgrep', '-f', 'subp_test.py'], stdout=PIPE)

    prev_pids=pgrep.communicate()[0].split()
    print 'previous processes:' , prev_pids

    for pid in prev_pids:
        if int(pid) !=int(my_pid):
            print 'killing', pid
            os.kill(int(pid), signal.SIGKILL)

    # do the job
    subprocess.call('python subp_test.py 1', shell=True)
    subprocess.call('python subp_test.py 2', shell=True)
    subprocess.call('python some_other_script.py', shell=True)

else:
    p_num = sys.argv[1]
    for i in range(20):
        time.sleep(1)
        print 'child', p_num, \
            "pid:", os.getpid(), \
            "pgid:", os.getgid(), \
            ":", i

This will kill all processes that have the substring 'subp_test.py' in its command but will not kill some_other_script.py or other programs without the 'subp_test.py' in it.

The calls the script subp_test.py will execute are unexpected but as I understand, they are supposed to be under it in the process tree.

So how do I access all the children of subp_test.py in order to kill them when a new instance of subp_test.py begins to run?

Also, are there better approaches to implement this logic?

I use Python 2.6.5 on Ubuntu 10.04.

Run your program under a new session group and write the session group id to a file. When your program starts, kill -SIGNAL -prevsessiongroup. This will kill all processes and their children etc unless one of them explicitly changes the session group. I have included urls which contain snippets of code you can use.

https://docs.python.org/2/library/os.html#os.setsid http://web.archive.org/web/20131017130434/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/

您可以使用此命令终止分配给 python 脚本的所有资源:

kill -9 `ps -ef | grep your_python_script.py | grep -v grep | awk '{print $2}'`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM