Python3实际上并没有杀死进程

时间:2017-10-09 20:32:55

标签: python python-3.x process

我正在从Python3运行一些进程,但它们没有被终止。这是问题的MCVE,在Linux 16.04上使用Python 3.5运行。我用QJoypad和Sublime3尝试过这个。

import subprocess
import time

p_joypad = subprocess.Popen(['qjoypad'])   # also happens with sublime3
time.sleep(2)                              # wait until process starts

p_joypad.terminate()                       # try and kill it

p_joypad.kill()                            # try and kill it again
del p_joypad

os.kill(p_joypad.pid, signal.SIGTERM)      # ask the OS to kill it
os.kill(p_joypad.pid, signal.SIGKILL)

# another attempt at calling and killing the process
p_joypad = subprocess.Popen(['qjoypad'], preexec_fn=os.setsid)
os.killpg(os.getpgid(p_joypad.pid), signal.SIGTERM)

input("Process is still open, baby")       # hang up to verify this

最初我只有terminate()调用,但后来我尝试了kill()以及从内存中清除对象。但是,此后两个进程仍在运行。 Qjoypad不允许调用其他实例(所以我需要关闭并重启我的Python3应用程序),这是非常有问题的。

1 个答案:

答案 0 :(得分:0)

好的,我发现了这个问题。我必须将shell设置为True并终止进程组。来自here

p_joypad = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
os.killpg(os.getpgid(p_joypad.pid), signal.SIGTERM)