LBEM-CH / focus

High Throughput Electron Microscopy Image Processing Software
http://www.focus-em.org
GNU General Public License v2.0
35 stars 14 forks source link

Kill everything called by the script when pressing the "stop" button #139

Open rdrighetto opened 8 years ago

rdrighetto commented 8 years ago

Whenever the user interrupts a script by clicking the "Stop" button, it should automatically kill all programs called by that script (e.g. Python scripts, FREALIGN instances). I know this can be very tricky and highly OS-dependent, but it would be really useful. For example, at the moment, the particle picking Python script can take a long time to run, and if the user stops the CSH script from the 2dx GUI, it keeps running the .py script in the background. This is very annoying and resource-consuming.

robbmcleod commented 8 years ago

If you are using Python's subprocess module to start the process, i.e. with popen, then the following code will kill all child processes of that subprocess. This is written in OO format. You might prefer to just track the process ID in csh and pass that in instead.

import subprocess, psutil

def kill(self):

    try:
        if bool( self.subprocess ):

            # Kill with psutil
            try:
                print( "Trying to kill subprocess pid %d" % self.subprocess.pid )
                os_process = psutil.Process( self.subprocess.pid )
                for child_process in os_process.children(recursive=True):
                    child_process.kill()
                os_process.kill()
            except Exception as e:
                print( "skulkHost.kill() psutil varient received exception: " + str(e) )

            # Now we have defunct zombie processes but they 
            # stop running.  Force garbage collection with del
            self.subprocess.communicate() # Get any remaining stdout
            self.subprocess.kill()
            del self.subprocess
    except Exception as e:
        print( "skulkHost.kill raised exception: " + str(e) )
nikhilbiyani commented 8 years ago

See http://stackoverflow.com/questions/28830103/qprocesskill-does-not-kill-children-in-linux