Kill a process and all its threads from the same process
Question: I am spawning a python process using MultiProcess library and within it I am
spawning around 100 threads( of 3 types each performing a separate function
and using a Queue).

I want my process to neatly terminate when a db flag is raised killing all the
threads and the process itself and also set a db level terminated flag once
everything's ended.

Here's my approach: As soon as a flag is set in the database( I can poll the
db at the end of the process code after spawning the threads), I can exit the
poll loop which exits my process. To kill all the threads, I'd have to keep an
array of thread-id's spawned and send a kill to all of them. I need that all
the threads will get killed along with their connections(threads are connected
to mysql,mongo and there's a websocket connection thread to another server).

If someone has a better approach or if there's any drawback in my approach,
please suggest.


Answer: This is something you can try, but no guarantee's . This function kill the
whole process tree.

    
    
    import psutil , os
    def kill_proc_tree(pid, including_parent=True):    
        parent = psutil.Process(pid)
        for child in parent.get_children(recursive=True):
            child.kill()
        if including_parent:
            # Set the db terminate flag.
    
            # the next step will kill the whole process
            parent.kill()
    
    # when Db flag iss set run this function
    def terminate():
        me = os.getpid()
        kill_proc_tree(me)
    

