2

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.

Max Segal
  • 1,955
  • 1
  • 24
  • 53
  • if you can get the subp_test.py pid, you can also query the tail of the process, psutil.Process should work http://stackoverflow.com/questions/40509813/get-pid-of-recursive-subprocesses?noredirect=1#comment68261789_40509813 and also pstree http://unix.stackexchange.com/questions/67668/elegantly-get-list-of-descendant-processes – Ari Gold Nov 14 '16 at 13:52

2 Answers2

1

you can use this command to kill all resources allocated to the python script:

kill -9 `ps -ef | grep your_python_script.py | grep -v grep | awk '{print $2}'`
Taha Hamedani
  • 105
  • 1
  • 11
0

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/

codegrep_admin
  • 519
  • 4
  • 7