[PYTHON] Kill including small processes

Overview

A tool for killing, including small processes. For python. (It is tied up in the python process.) Verification is done only on linux.

How to use If you execute it as it is, a list of parent processes with small processes will be displayed, so (As an example, assume that a program with a small process of proc_01.py proc_02.py is running.)

$ python terminate_children_process.py

List of processes with python related small processes
Specifying a PID on the command line terminates including small processes.
{'pid': 26727, 'cmdline': ['python', 'proc_01.py']}
{'pid': 26747, 'cmdline': ['python', 'proc_02.py']}

Specify the pid you want to end and execute again.

$ python terminate_children_process.py 26747

terminate child process 26849
terminate child process 26850
terminate child process 26851
terminate parent process 26747

Source (terminate_children_process.py)

#terminate_children_process.py
import sys
import psutil

if len(sys.argv)==1:
    #View process with python related small processes
    print("List of processes with python related small processes")
    print("Specifying a PID on the command line terminates including small processes.")
        
    PROCNAME = "python"
    for proc in psutil.process_iter([ "pid"  ,  'cmdline'  ]):
        if proc.name()[:len(PROCNAME)] == PROCNAME:
            p = psutil.Process(proc.pid)
            if len(p.children()) >0:
                print(proc.info)
    
else:
    #Terminate including the specified PID and its small processes
    
    target_pid=int(sys.argv[1])
    p = psutil.Process(target_pid)
    
    #Child terminate
    pid_list=[pc.pid for pc in p.children(recursive=True)] 
    for pid in pid_list:
        psutil.Process(pid).terminate ()
        print("terminate child process{}" .format(pid))
    
    #Parent terminate
    p.terminate ()
    print("terminate parent process{}" .format(target_pid))

reference

psutil documentation

Recommended Posts

Kill including small processes
How to kill processes in bulk