简体   繁体   English

如何终止多处理父流程?

[英]How to Terminate Multiprocessing Parent Process?

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 子级获取父进程的PID,并使用psutil终止父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. 因此,如果按键x被按下,则子级应终止父级及其本身。

In this code the value exists only because originally I had a while loop in my Parent process to check for the value. 在此代码中,该value存在仅是因为最初我在Parent进程中有一个while循环来检查该值。 If the value is 1 then it performs a sys.exit() on the Parent process. 如果值为1,则它将在父进程上执行sys.exit()

But I'm trying to avoid using this method. 但是我试图避免使用这种方法。

Any suggestions? 有什么建议么?

you can use os module to get the ppid , and then .kill it . 您可以使用os模块获取ppid ,然后.kill.kill

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

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 . 对子进程进行编码,使其在检测到X时简单退出。让父进程偶尔通过p.is_alivep.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 通知孩子应该通过共享的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__')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM