By Denise


2019-07-11 18:06:21 8 Comments

How can I get my Child process to terminate the Parent process?

I was thinking something along the lines of...

Child gets Parent Process's PID and terminates the parent using psutil

Here's my code

from multiprocessing import Process, Value
import keyboard
import sys

def KeyboardScan(v):
    Paused = False
    while True:
        if keyboard.is_pressed('x'):
            v.value = 1
            print("Child Terminate")
            sys.exit()
    #Child process's code

if __name__ == "__main__":
    val = Value('i', 0)
    p = Process(target=KeyboardScan, args=(val,))
    p.start()

    #Parent process's code

So if the key x is pressed, the Child should terminate the Parent and itself.

In this code the value exists only because originally I had a while loop in my Parent process to check for the value. If the value is 1 then it performs a sys.exit() on the Parent process.

But I'm trying to avoid using this method.

Any suggestions?

2 comments

@bigh_29 2019-07-11 19:06:54

Consider using multiprocessing primitives to ensure a clean shutdown of both processes. Two ways to accomplish this:

  1. Code the child to simply exit when it detects the X. Have the parent occasionally check if the child process is still alive via p.is_alive or p.exitcode. If it isn't, then exit
  2. Move the keyboard detection back to the parent process. Signal that the child should exit by way of a shared multiprocessing.Event

You haven't said what your parent process is doing while the child is running. That impacts which of these two approaches is easier to utilize. I like the second approach because it feels right to me. I would rather have the parent deal with user input, and just have the child process do work that does not involve interacting with the user.

The code snippet below shows the second approach.

from multiprocessing import Process, Event
import atexit
import time
from random import randint

def child_main(e):
    print('Child process booted')
    while True:
        if e.is_set():
            print('Child process got terminate event. Exiting')
            return

        print('Child process doing some important work')
        time.sleep(1.0)

def parent_main():
    print("parent process booting")
    quit_event = Event()
    child = Process(target=child_main, args=(quit_event,))
    print('starting child')
    child.start()

    is_x_pressed = lambda: randint(0,8) == 0
    while True:
        print('Parent doing its thing')
        time.sleep(.5)

        if is_x_pressed():
            print("Parent detected X. Exiting")
            quit_event.set()
            return

if __name__== '__main__':
    def exit_hook():
        print('Parent process atexit handler')
    atexit.register(exit_hook)

    parent_main()
    print('parent exiting __main__')

@Adam.Er8 2019-07-11 18:11:18

you can use os module to get the ppid, and then .kill it.

try this:

from multiprocessing import Process, Value
import keyboard
import os
import signal
import sys
import psutil

def KeyboardScan(v):
    Paused = False
    while True:
        if keyboard.is_pressed('x'):
            v.value = 1
            print("Child Terminate")
            #os.kill(os.getppid(), signal.SIGTERM) # <=== if you don't have psutil
            # below 2 line depend on psutil
            p = psutil.Process(os.getppid())
            p.terminate()  #or p.kill()
            sys.exit()
    #Child process's code

if __name__ == "__main__":
    val = Value('i', 0)
    p = Process(target=KeyboardScan, args=(val,))
    p.start()

    #Parent process's code

@Denise 2019-07-11 18:15:17

Hi thanks for ur reply. I tried it and i received an error : AttributeError: module 'signal' has no attribute 'SIGKILL'

@Adam.Er8 2019-07-11 18:18:16

@Denise oh sorry, it's SIGTERM. editing.

@Adam.Er8 2019-07-11 18:19:58

@Denise and actually if you already have psutil, it might be best. editing again to use psutil :)

@Denise 2019-07-11 18:20:59

Thanks! the SIGTERM and psutil works like a charm :)

@ShadowRanger 2019-07-11 18:22:04

@Adam.Er8: I'd keep both plain os and psutil solutions; people who don't already have psutil will benefit from the os.kill solution.

@Adam.Er8 2019-07-11 18:24:16

@ShadowRanger good point, adding it back in with a comment

@bigh_29 2019-07-11 18:31:22

Unfortunately, this approach does not cleanly shutdown the parent. This might be a problem if the parent has open file handles or database connections.

@ShadowRanger 2019-07-11 18:39:19

@bigh_29: Sending signal.SIGINT (on Windows, signal.CTRL_C_EVENT) would fix that, by injecting a KeyboardInterrupt into the parent process, instead of hard killing it.

Related Questions

Sponsored Content

37 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

22 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3386208 View
  • 3474 Score
  • 22 Answer
  • Tags:   python directory

41 Answered Questions

[SOLVED] How to merge two dictionaries in a single expression?

41 Answered Questions

[SOLVED] How to make a flat list out of list of lists

38 Answered Questions

[SOLVED] How to print colored text in terminal in Python?

30 Answered Questions

[SOLVED] How do I check if a list is empty?

  • 2008-09-10 06:20:11
  • Ray Vega
  • 2318005 View
  • 3235 Score
  • 30 Answer
  • Tags:   python list

11 Answered Questions

[SOLVED] Multiprocessing vs Threading Python

25 Answered Questions

[SOLVED] How can I safely create a nested directory?

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

17 Answered Questions

[SOLVED] How to make a chain of function decorators?

Sponsored Content