Take the 2-minute tour ×

I have a python multiprocessing process which spawns subprocesses to run various commands. I want to wrap the process in another class which first terminates the subprocess if the parent process is terminated.

Here is what I have so far:

def f():
  current_process = multiprocessing.current_process()
  current_process.subprocess = subprocess.Popen(...) # execute command taking a lot of time to run.

class ProcessWrapper(Process):
  def __init__(self, function):
    super(ProcessWrapper, self).__init__(target=function)

  def terminate(self):
    if hasattr(self, 'subprocess'):
      self.subprocess.terminate() # never gets here
    super(ProcessWrapper, self).terminate()

def main():
  p = ProcessWrapper(f)

The problem appears to be that the subprocess is never attached to the parent process. What is the reason for that? What is the best way to achieve this?

share|improve this question
hasattr is a built-in function, not a method. Your code will raise an AttributeError when executing terminate. –  Alp Jan 27 at 0:58
Your edit still won't work. You want hasattr(self, 'subprocess'). –  Alp Jan 27 at 1:01
Fixed. That was a mishap from trying to post a shortened example of my code. –  Paul Baltescu Jan 27 at 1:03

1 Answer 1

up vote 1 down vote accepted

For clarity, let's use the following terms: The "parent process" is the initial Python process you start; the "child process" is the process you start via the multiprocessing module; the "grandchild process" is the process you start via subprocess.Popen.

The issue is that your f is executed in the child process, but when you invoke the terminate method of the ProcessWrapper instance you're running code in the parent process, where a subprocess attribute was never assigned to the object returned by multiprocessing.current_process().

To do what you want you could use process groups to enable the parent process to terminate the grandchild process directly, or (as a finer-grained, manual method) send a signal from the parent to the child and have a signal handler in the child terminate the grandchild.

share|improve this answer
Can you show me how to attach a handler to the child process to terminate the grandchild process? –  Paul Baltescu Jan 27 at 1:47

Your Answer


