2

I am using python multiprocessing library for creating new processes. The parent needs to identify the child processes so it can stop a particular process anytime. I can give the name to a process but is it possible to get a process handler, to stop it later, using name?

5
  • Are you creating all of the processes at one time or just when required? Commented Aug 14, 2015 at 14:09
  • Could you just put the processes in a dict, with the name as the key? Commented Aug 14, 2015 at 14:18
  • Please show a trimmed down of your work. That makes it easier for those who can help. Commented Aug 14, 2015 at 14:30
  • @dano Thanks. I also thought about that after posting the message. Commented Aug 14, 2015 at 14:40
  • @justcompile I need to create processes when required. Commented Aug 14, 2015 at 14:42

1 Answer 1

1

It seems that you are looking for the terminate() method on your multiprocessing.Process instance.

Example usage of some of the methods of Process:

>>> import multiprocessing, time, signal
>>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
>>> print(p, p.is_alive())
<Process(Process-1, initial)> False
>>> p.start()
>>> print(p, p.is_alive())
<Process(Process-1, started)> True
>>> p.terminate()
>>> time.sleep(0.1)
>>> print(p, p.is_alive())
<Process(Process-1, stopped[SIGTERM])> False
>>> p.exitcode == -signal.SIGTERM
True

If you are trying to get an active process by name, you could use the following function:

def get_process(name):
    return next((p for p in multiprocessing.active_children() if p.name == name), None)
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I was looking for a function to get a process by name. I will store the processes in a dictionary and later use that to terminate the specific process.
@UsmanIjaz A function has been added for getting a process by name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.