Search code examples
pythonmultiprocessingpython-multiprocessingpool

How to terminate multiprocessing Pool processes?


I'm working on a renderfarm, and I need my clients to be able to launch multiple instances of a renderer, without blocking so the client can receive new commands. I've got that working correctly, however I'm having trouble terminating the created processes.

At the global level, I define my pool (so that I can access it from any function):

p = Pool(2)

I then call my renderer with apply_async:

for i in range(totalInstances):
    p.apply_async(render, (allRenderArgs[i],args[2]), callback=renderFinished)
p.close()

That function finishes, launches the processes in the background, and waits for new commands. I've made a simple command that will kill the client and stop the renders:

def close():
    '''
        close this client instance
    '''
    tn.write ("say "+USER+" is leaving the farm\r\n")
    try:
        p.terminate()
    except Exception,e:
        print str(e)
        sys.exit()

It doesn't seem to give an error (it would print the error), the python terminates but the background processes are still running. Can anyone recommend a better way of controlling these launched programs?


Solution

  • Found the answer to my own question. The primary problem was that I was calling a third-party application rather than a function. When I call the subprocess [either using call() or Popen()] it creates a new instance of python whose only purpose is to call the new application. However when python exits, it will kill this new instance of python and leave the application running.

    The solution is to do it the hard way, by finding the pid of the python process that is created, getting the children of that pid, and killing them. This code is specific for osx; there is simpler code (that doesn't rely on grep) available for linux.

    for process in pool:
        processId = process.pid
        print "attempting to terminate "+str(processId)
        command = " ps -o pid,ppid -ax | grep "+str(processId)+" | cut -f 1 -d \" \" | tail -1"
        ps_command = Popen(command, shell=True, stdout=PIPE)
        ps_output = ps_command.stdout.read()
        retcode = ps_command.wait()
        assert retcode == 0, "ps command returned %d" % retcode
        print "child process pid: "+ str(ps_output)
        os.kill(int(ps_output), signal.SIGTERM)
        os.kill(int(processId), signal.SIGTERM)