环境:Raspberry Pi Wheezy
我有一个Python程序,它使用Popen调用另一个Python程序
from subprocess import *
oJob = Popen('sudo python mypgm.py',shell=True)
另一个菜单选项应该立即结束作业
oJob.kill()
但作业仍在运行?
最佳答案
当您添加选项 shell=True
时,python 会启动一个 shell,而该 shell 又会启动进程 python mymgm.py
。您正在此处终止 shell 进程,该进程不会终止运行 mymgm.py 的自己的子进程。
为了确保子进程在 oJob.kill
上被杀死,您需要将它们全部分组到一个进程组下,并让 shell 进程成为组的领导者。
代码是,
import os
import signal
import subprocess
# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,
shell=True, preexec_fn=os.setsid)
os.killpg(pro.pid, signal.SIGTERM) # Send the signal to all the process groups
当您向 shell 进程发送 SIGTERM
信号时,它也会杀死其所有子进程。
关于python - Popen 没有响应杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30387180/