Killing child process when parent crashes in python

前端 未结 1 2015
無奈伤痛
無奈伤痛 2020-12-03 15:17

I am trying to write a python program to test a server written in C. The python program launches the compiled server using the subprocess module:



        
相关标签:
1条回答
  • 2020-12-03 15:38

    I would atexit.register a function to terminate the process:

    import atexit
    process = subprocess.Popen(args.server_file_path)
    atexit.register(process.terminate)
    pid = process.pid
    

    Or maybe:

    import atexit
    process = subprocess.Popen(args.server_file_path)
    @atexit.register
    def kill_process():
        try:
            process.terminate()
        except OSError:
            pass #ignore the error.  The OSError doesn't seem to be documented(?)
                 #as such, it *might* be better to process.poll() and check for 
                 #`None` (meaning the process is still running), but that 
                 #introduces a race condition.  I'm not sure which is better,
                 #hopefully someone that knows more about this than I do can 
                 #comment.
    
    pid = process.pid
    

    Note that this doesn't help you if you do something nasty to cause python to die in a non-graceful way (e.g. via os._exit or if you cause a SegmentationFault or BusError)

    0 讨论(0)
提交回复
热议问题