Ensuring subprocesses are dead on exiting Python program

后端 未结 14 1706
有刺的猬
有刺的猬 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:29

    Find out a solution for linux (without installing prctl):

    def _set_pdeathsig(sig=signal.SIGTERM):
        """help function to ensure once parent process exits, its childrent processes will automatically die
        """
        def callable():
            libc = ctypes.CDLL("libc.so.6")
            return libc.prctl(1, sig)
        return callable
    
    
    subprocess.Popen(your_command, preexec_fn=_set_pdeathsig(signal.SIGTERM)) 
    

提交回复
热议问题