Reputation: 1539
In my (very simplified) scenario, in python 2.7, I have 2 processes:
Creation of child process:
killer = multiprocessing.Process(...)
killer.start()
The child process executes the following code after X time (simplified version of the code):
process = psutil.Process(parent_pid)
...
if time_elapsed:
while True:
process.kill()
if not process.is_alive:
exit()
The problem is that it's leaving the parent as a zombie process, and the child is never exiting because the parent is still alive.
The same code works as expected in Windows.
All the solutions that I saw were talking about the parent process waiting for the child to finish by calling killer.join()
, but in my case, the parent is the one who does the task, and it shouldn't wait for its child.
What is the best way to deal with a scenario like that?
Upvotes: 11
Views: 8615
Reputation: 1844
You could use os.getppid()
to retrieve the parent's PID, and kill it with os.kill()
.
E.g. os.kill(os.getppid(), signal.SIGKILL)
See https://docs.python.org/2/library/os.html and https://docs.python.org/2/library/signal.html#module-signal for reference.
A mwo:
Parent:
import subprocess32 as subprocess
subprocess.run(['python', 'ch.py'])
Child:
import os
import signal
os.kill(os.getppid(), signal.SIGTERM)
Upvotes: 9