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?
-
Are you creating all of the processes at one time or just when required?justcompile– justcompile2015-08-14 14:09:17 +00:00Commented Aug 14, 2015 at 14:09
-
Could you just put the processes in a dict, with the name as the key?dano– dano2015-08-14 14:18:23 +00:00Commented Aug 14, 2015 at 14:18
-
Please show a trimmed down of your work. That makes it easier for those who can help.Hai Vu– Hai Vu2015-08-14 14:30:50 +00:00Commented Aug 14, 2015 at 14:30
-
@dano Thanks. I also thought about that after posting the message.Usman Ijaz– Usman Ijaz2015-08-14 14:40:55 +00:00Commented Aug 14, 2015 at 14:40
-
@justcompile I need to create processes when required.Usman Ijaz– Usman Ijaz2015-08-14 14:42:28 +00:00Commented Aug 14, 2015 at 14:42
Add a comment
|
1 Answer
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)
2 Comments
Usman Ijaz
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.
Noctis Skytower
@UsmanIjaz A function has been added for getting a process by name.