Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing parent process from a child process with Python on Linux

In my (very simplified) scenario, in python 2.7, I have 2 processes:

  1. Parent process, which doing some tasks.
  2. Child process, which needs to kill the parent process after X time.

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?

like image 771
macro_controller Avatar asked Jul 12 '18 12:07

macro_controller


People also ask

How do you kill a process in Linux Python?

If the program is the current process in your shell, typing Ctrl-C will stop the Python program.

How do you kill a child process in Python?

You can kill all child processes by first getting a list of all active child processes via the multiprocessing. active_children() function then calling either terminate() or kill() on each process instance.

How do you kill a process and all child processes in Linux?

If it is a process group you want to kill, just use the kill(1) command but instead of giving it a process number, give it the negation of the group number. For example to kill every process in group 5112, use kill -TERM -- -5112 .

How do you end a process in Python multiprocessing?

We can kill or terminate a process immediately by using the terminate() method. We will use this method to terminate the child process, which has been created with the help of function, immediately before completing its execution.


Video Answer


1 Answers

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)
like image 71
Bacon Avatar answered Oct 20 '22 15:10

Bacon