Reputation: 43
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?
Upvotes: 2
Views: 103
Reputation: 22011
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)
Upvotes: 1