可以,但是有问题。即使在您放弃它之后,该过程仍将继续执行您要求它执行的任何操作。如果你真的希望它停止,你必须在放弃它后向它发送一个信号来杀死它。
由于您正在生成一个新进程(./configure,这可能是一个配置脚本),这反过来又会创建大量子进程,这将变得更加复杂。
import os
def runTestCmd(self):
self.proc = subprocess.Popen(["./configure"], shell=False,
preexec_fn=os.setsid)
然后os.kill(-process.pid, signal.SIGKILL) 应该杀死所有的子进程。基本上你正在做的是使用preexec_fn 使你的新子进程到acquire it's own session group。然后,您将向该会话组中的所有进程发送信号。
许多产生子进程的进程都知道他们需要在子进程死亡之前清理它们。因此,如果可以的话,您应该尝试对他们友善。先试试os.signal(-process.pid, signal.SIGTERM),等待一两秒让进程退出,然后再试试SIGKILL。像这样的:
import time, os, errno, signal
def waitTestComplete(self, timeout):
st = time.time()
while (time.time()-st) < timeout:
if self.proc.poll() is not None: # 0 just means successful exit
# Only return True if process exited successfully,
# otherwise return False.
return self.proc.returncode == 0
else:
time.sleep(2)
# The process may exit between the time we check and the
# time we send the signal.
try:
os.kill(-self.proc.pid, signal.SIGTERM)
except OSError, e:
if e.errno != errno.ESRCH:
# If it's not because the process no longer exists,
# something weird is wrong.
raise
time.sleep(1)
if self.proc.poll() is None: # Still hasn't exited.
try:
os.kill(-self.proc.pid, signal.SIGKILL)
except OSError, e:
if e.errno != errno.ESRCH:
raise
raise TestError("timed out waiting for test to complete")
附带说明,永远不要使用shell=True,除非您绝对确定这是您想要的。严重地。 shell=True 非常危险,是许多安全问题和神秘行为的根源。