且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中干净地杀死子进程

更新时间:2022-06-08 20:48:01

这里有2个主要问题:

第一个问题:如果您使用的是 shell = True ,那么您将杀死运行进程的 shell ,而不是进程本身.父进程被杀死后,子进程将失效/不会立即被终止.

First issue: If you're using shell=True, so you're killing the shell running the process, not the process itself. With its parent killed, the child process goes defunct / isn't killed immediately.

在您的情况下,您使用的不是内置的 sleep ,因此您可以删除 shell = True Popen 将产生实际的进程ID: p.terminate()将起作用.

In your case, you're using sleep which is not built-in, so you could drop shell=True, and Popen would yield the actual process id: p.terminate() would work.

您可以(并且应该)在大多数情况下避免使用 shell = True ,即使它需要额外的python编码工作(将2个命令一起使用,重定向输入/输出,所有这些情况都可以)可以由一个或几个 Popen 没有 shell = True 很好地处理.

You can (and you should) avoid shell=True most of the time, even if it requires extra python coding effort (piping 2 commands together, redirecting input/output, all those cases can be nicely handled by one or several Popen without shell=True.

(第二个问题),如果该修复程序结束后该进程仍然无效,则可以调用 p.wait()(来自

And (second issue) if the process is still defunct when terminating after that fix, you could call p.wait() (from this question). Seems that calling terminate isn't enough. The Popen object needs to be garbage collected.