Ensuring subprocesses are dead on exiting Python program

后端 未结 14 1730
有刺的猬
有刺的猬 2020-12-02 09:17

Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().

If not, should

14条回答
  •  生来不讨喜
    2020-12-02 09:37

    Warning: Linux-only! You can make your child receive a signal when its parent dies.

    First install python-prctl==1.5.0 then change your parent code to launch your child processes as follows

    subprocess.Popen(["sleep", "100"], preexec_fn=lambda: prctl.set_pdeathsig(signal.SIGKILL))
    

    What this says is:

    • launch subprocess: sleep 100
    • after forking and before exec of the subprocess, the child registers for "send me a SIGKILL when my parent terminates".

提交回复
热议问题