Usman Ijaz
Usman Ijaz

Reputation: 43

Process identification using python multiprocessing library

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

Answers (1)

Noctis Skytower
Noctis Skytower

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

Related Questions