Ensuring subprocesses are dead on exiting Python program

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

    The subprocess.Popen.wait() is the only way to assure that they're dead. Indeed, POSIX OS's require that you wait on your children. Many *nix's will create a "zombie" process: a dead child for which the parent didn't wait.

    If the child is reasonably well-written, it terminates. Often, children read from PIPE's. Closing the input is a big hint to the child that it should close up shop and exit.

    If the child has bugs and doesn't terminate, you may have to kill it. You should fix this bug.

    If the child is a "serve-forever" loop, and is not designed to terminate, you should either kill it or provide some input or message which will force it to terminate.


    Edit.

    In standard OS's, you have os.kill( PID, 9 ). Kill -9 is harsh, BTW. If you can kill them with SIGABRT (6?) or SIGTERM (15) that's more polite.

    In Windows OS, you don't have an os.kill that works. Look at this ActiveState Recipe for terminating a process in Windows.

    We have child processes that are WSGI servers. To terminate them we do a GET on a special URL; this causes the child to clean up and exit.

提交回复
热议问题